我想反序列化如下输入:
{
"NameFilter": ["John", "Paul"], # name has to be exactly 4 letters length
"AgeFilter": [
{
"Min": 10,
"Max": 12
},
{
"Min": 8,
"Max": 99
}
]
}
对于这样的事情:
{
'name_filter': ['John', 'Paul'],
'age_filter': ['10-12', '8-99']
}
为此,我创建了3个序列化器:
class NameFilterSerializer(serializers.Serializer):
name_filter = serializers.CharField(max_length=4, validators=[MinLengthValidator(4)])
def to_representation(self, instance):
return instance
class AgeFilter(serializers.Serializer):
min = serializers.IntegerField()
max = serializers.IntegerField()
def to_representation(self, instance):
return str(instance['Min']) + '-' + str(instance['Max'])
class FilterSerializer(serializers.Serializer):
name_filter = NameFilterSerializer(many=True)
age_filter = AgeFilter(many=True)
def to_internal_value(self, data):
return {
'name_filter': data['NameFilter'],
'age_filter': data['AgeFilter']
}
它返回正确的值,但是在输入数据无效的情况下(“ Min”不是数字或“ NameFilter”包含“ NameExceeding4letters”),它不会引发错误。我想念什么?
无效的数据示例:
{
"NameFilter": ["VeryLongName", "Paul"], # name has to be exactly 4 letters length
"AgeFilter": [
{
"Min": 'I am not an int',
"Max": 12
},
{
"Min": 8,
"Max": 99
}
]
}```
答案 0 :(得分:0)
您可以创建一个自定义序列化器字段,该字段在实际呈现资源之前呈现转换错误:
from django.utils import six
class ValidIntegerField(serializers.IntegerField):
def to_internal_value(self, data):
if isinstance(data, six.text_type):
raise serializers.ValidationError('Value should be a valid integer')
return super().to_internal_value(data)
然后在序列化器类定义中使用它:
class AgeFilter(serializers.Serializer):
min = ValidIntegerField()
max = ValidIntegerField()
def to_representation(self, instance):
return str(instance['Min']) + '-' + str(instance['Max'])
注意:有关six.text_type