问题
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