【发布时间】:2015-08-16 08:33:44
【问题描述】:
如何在 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'])
但是 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'.
我搜索了堆栈 DRF - ModelSerializer with a non-model write_only field 并找到了一些解决方案,但这些解决方案是指我使用 DRF 3 的 DRF 2。在这个版本上是否有解决方案?
【问题讨论】:
-
@chandu 那么这个问题在 3.0+ 中没有解决,还是现在有解决方案?
-
您可以使用此方法或以下方法django-rest-framework.org/api-guide/fields/…
-
我在您上面发布的答案中使用模型上的 @property 解决了它。您可以发帖并回答以便我接受吗?
标签: python django django-rest-framework