如何在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 …