DRF序列化程序深度会在创建时忽略字段

时间:2018-03-01 21:25:21

标签: python django django-rest-framework

(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个对象。

3 个答案:

答案 0 :(得分:0)

重要提示:我认为此方法非常复杂,因为任何人都可以编辑嵌套对象。

您可以使用drf-writable-nested来实现此类功能。如果有人需要,请更新the project on github

PS。一定要使用' pk'嵌套对象的字段,如果您不想创建这些对象。

答案 1 :(得分:0)

找到更好的解决方案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

PS。也致the project on github.

答案 2 :(得分:0)

class DemoSerializer(serializers.ModelSerializer):
def __init__(self, instance=None, data=empty, **kwargs):
    if instance:
        setattr(self.Meta, 'depth', 1)
    else:
        setattr(self.Meta, 'depth', 0)
    super(DemoSerializer, self).__init__(instance, data, **kwargs)

class Meta:
    model = Demo
    fields = '__all__'
    depth = 0