写入时是DRF PrimaryRelatedField,读取时是NestedSerializer? [英] DRF PrimaryRelatedField when write and NestedSerializer when read?
问题描述
我正在使用嵌套的序列化器.我需要 ProfileSerializer
返回完整的相关 Project
对象以获取请求,并考虑仅对id进行切换(更改当前值),就像relatedPrimaryField behaiviour一样,用于 ProfileSerializer
.关于如何实现这一目标的任何解决方案?
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')
推荐答案
如Linova所述,不使用第三方库即可解决此问题的最简单方法是在序列化程序中声明两个单独的字段.嵌套的序列化器 current
将保持不变,但是您将添加一个新的 PrimaryKeyRelatedField
序列化器.嵌套的序列化程序应该是只读的,但是相关字段不是只读的.我通常按照惯例将相关字段命名为< field> _id
.
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.
在GET请求中,将返回嵌套的序列化程序和 id
字段,但对于PUT或POST请求,只需指定< field> _id
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')
这篇关于写入时是DRF PrimaryRelatedField,读取时是NestedSerializer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!