1

I am hoping to return ids of newly created objects after deserialization. However, to do this, I have to serialize all newly created data again. If I don't, I get the data back but without the ids.

Isn't REST supposed to work that way - return to the caller what was created? If it should, am I missing something? The DRF tutorial left me with the impression that this should work (return the ids).

Here is code:

class ProjectView(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    def put(self, request, *args, **kwargs):
        ser = ProjectCreateSerializer(data=request.data, context={'user': request.user})
        if  ser.is_valid(raise_exception=True):
            proj = ser.save(user=request.user)
            #### The line below is required to get ids back to the user
            ser = ProjectCreateSerializer(proj)
            return Response(ser.data, status=status.HTTP_201_CREATED)
        return Response(status=status.HTTP_400_BAD_REQUEST)

I also have a create method on the ProjectCreateSerializer and it creates and saves the object before returning it.

EDIT

I would like to be able to

PUT /project/
{
'name': 'Demo'
}

and get back:

{
'id': 1,
'name': 'Demo'
}

in one shot, without deserialize --> data --> serialize.

David R.
  • 855
  • 8
  • 17
  • Might take a look at this answer: http://stackoverflow.com/questions/15014495/id-field-in-django-rest-framework-serializer – Brandon Taylor Jun 23 '15 at 01:38
  • 1
    This is a duplicate of [this question](http://stackoverflow.com/q/27858184/359284), but I'm out of flags for today. – Kevin Brown-Silva Jun 24 '15 at 23:35
  • @Kevin I ended up with `{'id': ['This field is required.']}`. Using DRF 3.1.3. – David R. Jun 25 '15 at 00:17
  • @ Kevin There is this bug reported [link](https://github.com/tomchristie/django-rest-framework/issues/2813), as a result if you have `read_only: False`, the `required` entry is ignored. This is in ModelSerializer.include_extra_kwargs. – David R. Jun 25 '15 at 00:32
  • Possible duplicate of [id field in django rest framework serializer](http://stackoverflow.com/questions/15014495/id-field-in-django-rest-framework-serializer) – Siyu Apr 14 '17 at 19:02

0 Answers0