(github上有这个问题的项目) https://github.com/sam-moshenko/drf_depth_problem
由于某种原因,序列化器的深度选项会使字段在创建时被忽略。
序列化器:
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('question', 'body',)
depth = 1
View:
class AnswerList(ListCreateAPIView):
queryset = Answer.objects.all()
serializer_class = AnswerSerializer
当我尝试创建答案时depth = 1
I get NOT NULL constraint failed: forum_answer.question_id
,但是当我注释掉时depth = 1
一切正常。但当然我没有得到完整的Question
对象,仅pk
of it.
找到了更好的解决方案here https://stackoverflow.com/a/33048798/3992237
现在序列化器看起来像这样:
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
附:还致力于github上的项目。 https://github.com/sam-moshenko/drf_depth_problem
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)