Reputation: 2085
Suppose i have this code
class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
Now Let us suppose that in my get, i need to modify request.data
def get(self, request, format=None):
data = modify(request.data)
request.data = data # This don't work as i can't set attribute on request
response = self.post(self, new_request, format=None) # i want to do post method now with new request
serializer = SnippetSerializer(snippets, many=True)
Is there any way to do that
Upvotes: 3
Views: 2797
Reputation: 1135
You could try something like this:
def get(self, request, format=None):
response = self.post(self, request, format=None, data=data ) # i want to do post method now with new request
serializer = SnippetSerializer(snippets, many=True)
Now your method post should be:
def post(self, request, format=None, **kwargs):
original_data = request.data
additional_data = kwargs.get('data') # now you will be able to do whatever you want
# more code goes here
Upvotes: 3
Reputation: 20986
You should not modify your data upon get as they are usually marked as "unsafe" because they modify the data state.
You don't want to mess with the provided request either. It often creates more issues than it solves and adds some magic.
If you want the serializer to have more data than the request sent you should pass them to the serializer's save function. They will be added to the validated_data and available in the serializer's create / update methods (http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save)
Upvotes: 0