使用DRF序列化程序验证字典列表

时间:2017-06-08 01:29:26

标签: django django-rest-framework

如何编写验证字典列表的序列化程序?

发送的样本有效负载是:

"payment_discount": [
    {
        "discount_rule_id": 1,
        "discount_rule_name": "10 day early payment",
        "discount_earned": "298.00"
    },
    {
        "discount_rule_id": 2,
        "discount_rule_name": "Store discount",
        "discount_earned": "5.50"
    },
]

this SO answerthis开始:

class PaymentDiscountSerializer(serializers.DictField):

    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

class PaymentDiscountListSerializer(serializers.ListField):
    """Serialize discount object"""
    child = PaymentDiscountSerializer()

class PaymentSerializer(serializers.ModelSerializer):
    payment_discount = PaymentDiscountListSerializer()
    # Other model fields

有了这个,我可以使用serializer.data访问有效负载中的payment_discount对象,但遗憾的是,如果例如没有对字典进行验证。有效负载包括discount_earned值,该值不是Decimal类型

使用:Django == 1.10.2& djangorestframework == 3.5.1

1 个答案:

答案 0 :(得分:5)

我认为你可以简化序列化程序...... Haven没有对它进行测试,但你可以使用类似的东西:

class PaymentDiscountSerializer(serializers.Serializer):
    """Serialize discounts"""
    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

class PaymentSerializer(serializers.ModelSerializer):
    payment_discount = PaymentDiscountSerializer(many=True)
    # Other model fields

它应该为您提供您想要的对象列表。

对于验证,它应该像这样开箱即用。

但是,我还没有测试过它。如果您的验证有问题,您可以定义自己的验证。 例如:

class PaymentDiscountSerializer(serializers.Serializer):
    """Serialize discounts"""
    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

    def validate_discount_rule_id(self, value):
        # Validation logic of the discount_rule_id field
        #
        return value

    def validate(self, attrs):
        # Validation logic of all the fields
        #
        return attrs

有关更多信息,请参阅http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation