Django-rest-framework 从 id 更新外键

Sas*_*gov 4 django-rest-framework

可以通过主键更新字段吗?

序列化器:

class HuntingDetailViewSerializer(serializers.ModelSerializer):

    species = HuntingSpeciesSerializer(many=True, read_only=True)
    technique = HuntingTechniqueTagSerializer()

    class Meta:
        model = HuntListing
        exclude = ('owner',)
Run Code Online (Sandbox Code Playgroud)

意见:

    listing_id = request.data.get('listing_id')
    listing = HuntListing.objects.get(id=listing_id)

    serializer = HuntingDetailViewSerializer(listing, data=request.data, partial=True)

    if serializer.is_valid():
        serializer.save()
Run Code Online (Sandbox Code Playgroud)

样本数据:

{"listing_id":9, "technique":1, ....}
Run Code Online (Sandbox Code Playgroud)

但我得到:

{'technique': {u'non_field_errors': [u'Invalid data. Expected a dictionary, but got int.']}}
Run Code Online (Sandbox Code Playgroud)

如果重写更新并将此参数更改为 technology_id,我在验证数据中看不到这一点:

def update(self, instance, validated_data):
    print(validated_data)
Run Code Online (Sandbox Code Playgroud)

Yur*_*aha 7

只需覆盖 to_representation

在你的情况下:

class HuntingDetailViewSerializer(serializers.ModelSerializer):

   species = HuntingSpeciesSerializer(many=True, read_only=True)

   class Meta:
       model = HuntListing
       exclude = ('owner',)


   def to_representation(self, instance):
       ret = super().to_representation(instance)
       ret['technique'] = HuntingTechniqueTagSerializer(instance.technique).data
       return ret
Run Code Online (Sandbox Code Playgroud)

现在您可以在 GET 调用上看到 obj,并且可以通过 id {"listing_id":9, "technique":1, ....} 更新/创建


Col*_*lds 6

问题在于technique = HuntingTechniqueTagSerializer(). 这会创建一个嵌套的序列化程序,因此当您尝试更新模型时,它需要一个嵌套的字典。如果您只是删除此行,它应该可以工作。但是,如果您想要嵌套视图,则必须创建单独的读/写序列化程序。

  • 如何实现这一目标(使用 pk 更新记录,同时保留嵌套视图)? (2认同)