Skip to main content
 首页 » 编程设计

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

2024年09月07日8JustinYoung

(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.