Django REST - 从自定义to_internal_value中为序列化器运行字段验证

时间:2016-10-27 21:40:44

标签: json django validation serialization django-rest-framework

我正在尝试序列化这样的JSON:

{
    "Some URL": "https://helloworld.com/",
    "Some Integer": 12
    "Some Dictionary": {
        "Nested Array": [...]
        "Nested Dictionary": {...}
    }
}

不允许编写带空格字段的序列化程序(当然因为Python变量),所以我试图将BaseSerializer子类化。

class MyNestedSerializer(serializers.BaseSerializer):

    def to_internal_value(self, data):
        nested_array = data.get('Nested Array')
        nested_dictionary = data.get('Nested Dictionary')

        # Validation
        ....
        ....

        return {
            'Nested Array': nested_array,
            'Nested Dictionary': nested_dictionary
        }

    def to_representation(self, instance):
        return {
            'Nested Array': instance['Nested Array'],
            'Nested Dictionary': instance['Nested Dictionary']
        }


class MySerializer(serializers.BaseSerializer):

    def to_internal_value(self, data):
        some_url = data.get('Some URL')
        some_integer = data.get('Some Integer')
        some_dictionary = data.get('Some Dictionary')

        # Validation
        ....
        nested_serializer = MyNestedSerializer(data=some_dictionary)
        nested_serializer.is_valid(raise_exception=True)
        ....

        return {
            'Some URL': some_url,
            'Some Integer': some_integer,
            'Some Dictionary': some_dictionary
        }

    def to_representation(self, instance):
        return {
            'Some URL': instance['Some URL']
            'Some Integer': instance['Some Integer']
            'Some Dictionary': instance['Some Dictionary']
        }

现在通常,我会在序列化程序(而不是BaseSerializer)中定义字段类型,如下所示:

class BasicSerializer(serializers.Serializer):
    some_integer = serializers.IntegerField(min_value=0)
    some_dictionary = serializers.DictField(child=serializers.CharField())

将进行字段验证。我想要的是让这些验证器在to_internal_value的实现中运行,而不是编写我自己的验证。重写已编写的内容是没有意义的,但我似乎无法弄清楚如何在我的BaseSerializer中运行基本验证。

1 个答案:

答案 0 :(得分:1)

Serializer类是subclass of BaseSerializer。因此,在这种情况下,您无需从BaseSerializer派生,而是可以使用Serializer

class MySerializer(serializers.Serializer):


    def to_internal_value(self, data):
        some_url = data.get('Some URL')
        some_integer = data.get('Some Integer')
        some_dictionary = data.get('Some Dictionary')

        # Validation
        ....
        nested_serializer = MyNestedSerializer(data=some_dictionary)
        nested_serializer.is_valid(raise_exception=True)
        ....

        return {
            'Some URL': some_url,
            'Some Integer': some_integer,
            'Some Dictionary': some_dictionary
        }

    def to_representation(self, instance):
        return {
            'Some URL': instance['Some URL']
            'Some Integer': instance['Some Integer']
            'Some Dictionary': instance['Some Dictionary']
        }