Python Django Rest Framework-发布到包含外键值的可写嵌套字段
DRF的新功能,到目前为止,它非常有用,文档也是如此。不过,我正试图了解这应该如何工作。我基本上是想在Python Django Rest Framework-发布到包含外键值的可写嵌套字段,python,django,django-rest-framework,Python,Django,Django Rest Framework,DRF的新功能,到目前为止,它非常有用,文档也是如此。不过,我正试图了解这应该如何工作。我基本上是想在POST上创建一个新的reputation对象,该对象有一个与foreignkey相关的字段intereid提及ID已存在 信誉对象已正确表示,如下所示: { "id": 5, "author": 1, "authorname": "name", "value": 100, "mentionid": { "id": 1, "
POST
上创建一个新的reputation
对象,该对象有一个与foreignkey相关的字段intereid
<代码>提及ID已存在
信誉对象已正确表示,如下所示:
{
"id": 5,
"author": 1,
"authorname": "name",
"value": 100,
"mentionid": {
"id": 1,
"author": 1,
"somekey": "some value"
}
}
但当我发布时,我收到了以下错误:
默认情况下,`.create()`方法不支持可写嵌套字段。
为序列化程序“quickstart.serializers.ReputationSerializer”编写一个显式的“.create()”方法,或在嵌套的序列化程序字段上设置“read\u only=True”。
我假设我需要在序列化程序中定义一个create方法,但是出于好奇,我注意到如果我注释掉引用提及序列化程序的行,我可以成功地发布提及ID
字段,但是它返回一个只包含提及ID
外键值的对象,这不是我想要的。所以我很好奇我的模型中是否遗漏了一个可以解决问题的参数。也许我需要在我的模型中设置外键的默认值?谢谢你的洞察力
{
"id": 5,
"author": 1,
"authorname": "name",
"value": 100,
"mentionid": 1
}
我的模型有一个声誉等级:
class Reputation(models.Model):
mentionid = models.ForeignKey(Mention)
我有一个序列化程序:
class ReputationSerializer(serializers.ModelSerializer):
mentionid = MentionSerializer()
class Meta:
model = Reputation
fields = ('id', 'author', 'authorname', 'value', 'mentionid')
所以我想出了一个解决方案
这里的想法是有一个字段child\u id
,该字段是只写的,它接受一个设置sinetiid
源的值
class ReputationSerializer(serializers.ModelSerializer):
mentionid = MentionSerializer()
child_id = serializers.PrimaryKeyRelatedField(queryset=Mention.objects.all(), source='mentionid', write_only=True)
class Meta:
model = Reputation
fields = ('id', 'author', 'authorname', 'value', 'mentionid', 'child_id', 'created_date', 'published_date')