Last active
April 29, 2019 06:37
-
-
Save dz0/90fe8a899f5314144f6e5ccf995b8545 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InjectUrlDataMixin: | |
"""Used for POST on nested router (so it can take infromation from URL instead of repeting in serializer). | |
overrides `get_serializer` | |
(ps.: does not make sense for PUT/PATCH -- as the instance is selected by url-kwargs) | |
""" | |
def get_serializer(self, *args, **kwargs): | |
# standart `get_serializer` logic | |
serializer_class = self.get_serializer_class() | |
kwargs['context'] = self.get_serializer_context() | |
# our logic | |
if self.request.method == 'POST': | |
# prepare/clone data container (QueryDict) | |
data = kwargs.get('data', {}) # get data or create new {} | |
data = data.copy() # make a copy (as better not to change `request.data` QueryDict) | |
kwargs['data'] = data # and assign back into kwargs | |
# inject info from url-kwargs | |
url_kwargs = self.kwargs # this info also resides in kwargs['context']['view'] | |
for key, val in url_kwargs.items(): | |
data.setdefault(key, val) # don't overrite if exists | |
return serializer_class(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment