本文介绍了在DRF 3中的ModelSerializer上添加非模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在DRF 3中的ModelSerializer上添加非模型字段?例如,添加我的实际模型中不存在的字段?

How do add a non-model field on a ModelSerializer in DRF 3? i.e. add a field that does not exist on my actual model?

class TestSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='vote_detail')
    non_field = serializers.CharField()  # no corresponding model property.


    class Meta:
        model = vote_model
        fields = ("url", "non_field")

    def create(self, validated_data):
      print(direction=validated_data['non_field'])

但是DRF 3给我一个错误:

But DRF 3 gives me the error:

Got AttributeError when attempting to get a value for field `non_field` on serializer `TestSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Test` instance.
Original exception text was: 'Test' object has no attribute 'non_field'.

我已经搜索了堆栈,并找到了一些解决方案,但这些解决方案都引用了DRF 2,其中我正在使用DRF 3.在此版本上是否有解决方案?

I have searched stack DRF - ModelSerializer with a non-model write_only field and found a few solutions but these refer to DRF 2 where I'm using DRF 3. Is there a solution for this on this version?

推荐答案

class TestSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='vote_detail')
    non_field = serializers.SerializerMethodField()  # no corresponding model property.

    class Meta:
        model = vote_model
        fields = ("url", "non_field")

    def create(self, validated_data):
        print(direction=validated_data['non_field'])

或通过以下

这篇关于在DRF 3中的ModelSerializer上添加非模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 18:33