相关疑难解决方法(0)

在DRF 3中的ModelSerializer上添加非模型字段

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

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'])
Run Code Online (Sandbox Code Playgroud)

但是DRF 3给了我错误:

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'.
Run Code Online (Sandbox Code Playgroud)

我已经使用非模型write_only字段搜索了堆栈DRF - ModelSerializer,并找到了一些解决方案,但这些解决方案是指我正在使用DRF 3的DRF …

python django django-rest-framework

28
推荐指数
2
解决办法
2万
查看次数

标签 统计

django ×1

django-rest-framework ×1

python ×1