如何使rest_framework序列化程序不允许多余的字段? [英] How to make a rest_framework Serializer disallow superfluous fields?
问题描述
我已经注意到,在拒绝带有未知字段的输入时,串行器并不十分严格:
I've noticed that the Serializer isn't really strict when it comes to rejecting input with unknown fields:
In [1]: from rest_framework import serializers
In [2]: class TestSerializer(serializers.Serializer):
...: foo = serializers.CharField()
...:
In [3]: s = TestSerializer(data=dict(foo='foo', bar='bar'))
In [4]: s.is_valid()
Out[4]: True
在这种情况下,是否可以配置Serializer
以返回有关bar
意外的验证错误?
Is there a way to configure the Serializer
to return a validation error about bar
being unexpected in this situation?
推荐答案
这绝对有效:
class TestSerializer(serializers.Serializer):
foo = serializers.CharField()
def validate(self, attrs):
unknown = set(self.initial_data) - set(self.fields)
if unknown:
raise ValidationError("Unknown field(s): {}".format(", ".join(unknown)))
return attrs
嵌套和列出序列化器
如果您将这样的序列化程序用作另一个序列化程序中的字段,则此方法将无效.在这种情况下,子序列化器将无法访问初始数据,并且您将获得异常.
This will not work if you use a such a serializer as a field in another serializer. In which case, the child serializer won't have access to initial data and you will get an exception.
与ListSerializer
(或many=True
)相同,因为列表序列化程序的子序列化程序不会获得单独的initial_data
项(有一个github
Same with a ListSerializer
(or many=True
) as the list serializer's child serializer won't get the individual initial_data
items (there is a github ticket for this).
在那种情况下,在所有情况下都适用的较不干净的解决方案是:
In that case the slightly less clean solution which works all both cases is:
from rest_framework.fields import empty
from rest_framework.settings import api_settings
class TestSerializer(serializers.Serializer):
foo = serializers.CharField()
def run_validation(self, data=empty):
if data is not empty:
unknown = set(data) - set(self.fields)
if unknown:
errors = ["Unknown field: {}".format(f) for f in unknown]
raise serializers.ValidationError({
api_settings.NON_FIELD_ERRORS_KEY: errors,
})
return super(TestSerializer, self).run_validation(data)
这篇关于如何使rest_framework序列化程序不允许多余的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!