3

I am using a nested serializer. I need ProfileSerializer to return full related Project object for get requests and consider only id switching (changing current) like with relatedPrimaryField behaiviour for post/put requests on ProfileSerializer. any solutions on how to achieve this ?

class ProfileSerializer(serializers.ModelSerializer):
    current = ProjectSerializer()
    class Meta:
        model = Profile
        fields = ('function', 'current')
Clean coder
  • 147
  • 1
  • 9

2 Answers2

6

As Linova mentioned, the easiest way to solve this issue without using a third-party library is to declare two separate fields in your serializer. Your nested serializer current would stay the same, but you would add a new PrimaryKeyRelatedField serializer. The nested serializer should be read only, but the related field would not be read only. I normally name the related field <field>_id by convention.

In GET requests, both the nested serializer and the id field will be returned, but for PUT or POST requests only the <field>_id needs to be specified.

class ProfileSerializer(serializers.ModelSerializer):
    current = ProjectSerializer(read_only=True)
    current_id = serializers.PrimaryKeyRelatedField(queryset=Projects.objects.all(), source='current')
    class Meta:
        model = Profile
        fields = ('function', 'current', 'current_id')
natbob1
  • 308
  • 1
  • 11
3

The most consistent way I usually advice is to mark all the nested serializer (ProjectSerializer in this case) as read_only and add the id field as read_only=False

You'll therefore have consistence between the list/retrieve and creation/updates.

Linovia
  • 19,812
  • 4
  • 47
  • 48
  • How would you call that field (current_id) ? do you think there is no cleaner way to achieve this like adding an attribute to the nested serializer field telling them to switch to priamryrelatedfield when needed ? – Clean coder Mar 16 '17 at 12:19
  • Yes this can be have a different behavior for reading and writing. iirc, there's a third party package for that (http://www.django-rest-framework.org/topics/third-party-packages/) however we advice not to to avoid inconsistencies. – Linovia Mar 16 '17 at 12:24
  • @Linovia "not to avoid inconsistencies". Upvote for triple negative. – AlxVallejo Jul 21 '20 at 21:43
  • you could override to_representation and replace 'current' with the serialized version you want – user2457199 Jun 08 '22 at 01:54