fangsterr
fangsterr

Reputation: 3830

django-rest-framework: Serializer data's "id" field returns null

So I have an ObjectSerializer, which has a field for the 'id' field of the model Object (it's a ModelSerializer). Here's what's happening:

serializer = ObjectSerializer(data=request.DATA)
if serializer.is_valid():
  some_dict = {'field': serializer.data['field']}
  serializer.save()
  return Response(serializer.data, status=status.HTTP_201_CREATED)

The response's 'id' field returns null for some reason? When I remove the line with some_dict, the response returns the id okay.

Not really sure what's going on here. Any pointers would be much appreciated.

Upvotes: 2

Views: 2835

Answers (1)

Carlton Gibson
Carlton Gibson

Reputation: 7386

This is curious. The default implementation of the rest_framework.serializers.BaseSerializer data property just lazily populates the (private) _data member and returns that. Calling it twice in succession — which is essentially what you're doing — should return the same value the second time.

Can you reduce this to a failing test case and submit an issue on Github? — That would really help.

Update

Thanks for the report.

As Tom noted in the discussion you're seeing the issue because when you're accessing the data save() wasn't yet called, and so the id wasn't set. — Move the call to data after save() and you'd get the result you wanted.

Further to that, the behaviour has now been altered so that the cached data is cleared on a call to save() — this is fixed in master and should be in the next release.

Upvotes: 2

Related Questions