[Django]-Using DRF serializer to validate a list of dictionaries

10👍

I think you can simplify your serializers…
Haven’t tested it but you could use something like this:

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

It should give you a list of object like you want.

For the validation, it should work right out of the box like this.

But again, I haven’t tested it. If you are having problems with your validations, you can define your own.
Example:

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

see http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation for more infos.

Leave a comment