DRF PrimaryRelatedField when write and NestedSerializer when read?

两盒软妹~` 提交于 2021-01-05 06:40:34

问题


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

回答1:


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()
    current_id = serializers.PrimaryKeyRelatedField(queryset=Projects.objects.all(), source='current')
    class Meta:
        model = Profile
        fields = ('function', 'current', 'current_id')



回答2:


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.



来源:https://stackoverflow.com/questions/42833368/drf-primaryrelatedfield-when-write-and-nestedserializer-when-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!