[Django]-DRF PrimaryRelatedField when write and NestedSerializer when read?

7👍

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')

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.

Leave a comment