gpt4 book ai didi

python - DRF 序列化器深度使字段在创建时被忽略

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:38 25 4
gpt4 key购买 nike

(project is available on github with that problem)

出于某种原因,序列化程序的深度选项会在创建时忽略字段。

序列化器:

class AnswerSerializer(serializers.ModelSerializer):

class Meta:
model = Answer
fields = ('question', 'body',)
depth = 1

查看:

class AnswerList(ListCreateAPIView):
queryset = Answer.objects.all()
serializer_class = AnswerSerializer

当我尝试使用 depth = 1 创建答案时,我得到 NOT NULL constraint failed: forum_answer.question_id,但是当我注释掉 depth = 1 一切正常。但是当然我没有得到完整的 Question 对象,只有它的 pk

最佳答案

找到更好的解决方案here

现在序列化器看起来像这样:

class AnswerSerializer(serializers.ModelSerializer):
question_pk = serializers.PrimaryKeyRelatedField(
queryset=Question.objects.all(), source='question', write_only=True
)

class Meta:
model = Answer
fields = ('question', 'question_pk', 'body',)
depth = 1

附言。也致力于the project on github.

关于python - DRF 序列化器深度使字段在创建时被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49058931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com