[英]Django Rest Framework - Posting to writable nested field containing a Foreign Key value
DRF的新功能,到目前為止,它非常有用,文檔也非常有用。但是,我想盡一切辦法。 基本上,我想,在POST
創建一個新的reputation
,有一個外鍵相關的領域對象mentionid
。 mentionid
已經存在。
信譽對象正確表示,如下所示:
{
"id": 5,
"author": 1,
"authorname": "name",
"value": 100,
"mentionid": {
"id": 1,
"author": 1,
"somekey": "some value"
}
}
但是當我發布時收到此錯誤:
The `.create()` method does not support writable nestedfields by default. Write an explicit `.create()` method for serializer `quickstart.serializers.ReputationSerializer`, or set `read_only=True` on nested serializer fields.
我假設我需要定義的串行化器創建的方法,但出於好奇,如果我注釋掉引用我注意到MentionSerializer
我可以成功發布了mentionid
領域,但它只是返回一個對象mentionid
外鍵值,這不是我想要的。 所以我很好奇我是否在模型中缺少可以解決問題的參數。 也許我需要在模型中的外鍵上設置默認值? 感謝您的任何見解。
{
"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')
所以我想出了一個使用PrimaryKeyRelatedField的解決方案
這里的想法是讓child_id
字段是只寫的,它接受一個值來設置mentionid
源
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.