Return created object but with fewer fields

291 views
Skip to first unread message

Norbert P

unread,
Dec 6, 2014, 6:48:48 PM12/6/14
to django-res...@googlegroups.com
When creating and object in POST method how do you return only a few fields of created object? This is taken from the documentation:

    def post(self, request, format=None):
            serializer
= SnippetSerializer(data=request.data)
           
if serializer.is_valid():
                serializer
.save()
               
return Response(serializer.data, status=status.HTTP_201_CREATED)
           
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


Here `serializer.data` includes all of the fields defined in serializer but I only want to return just a few of them.

Tom Christie

unread,
Dec 7, 2014, 2:39:59 AM12/7/14
to django-res...@googlegroups.com
Either:

* Consider using write_only=True on the fields you don't want as output.
* Use a different serializer for returning the response to the one you us for validation.
* Just return the response data directly, without using a serializer.

Norbert P

unread,
Dec 7, 2014, 3:21:58 AM12/7/14
to django-res...@googlegroups.com
Thanks very much for the reply Tom. Also thanks for the effort you put for DRF. 
Reply all
Reply to author
Forward
0 new messages