Search code examples
pythonmarshmallow

Validating list elements are unique in marshmallow


I would like to understand if I can use marshmallow validate function to check whether all elements in a list are unique.

I have the following schema:

from marshmallow import Schema, fields, validate

class PaymentSchema(Schema):
    ...
    currencies = fields.List(
        fields.String(
            required=True,
            validate=[
                validate.OneOf(["USD", "EUR", "AUS", "GBP"]),
                validate.Length(min=1, max=4)
            ]
        )
    )

Is there any possibility to guarantee that given a list of currencies with duplicated currencies (["USD", "EUR", "EUR"]) raises a ValidationError?

Thanks!


Solution

  • The validates decorator allows custom validation:

    from marshmallow import Schema, ValidationError, fields, validate, validates
    
    class PaymentSchema(Schema):
        currencies = fields.List(
            fields.String(
                required=True,
                validate=[
                    validate.OneOf(["USD", "EUR", "AUS", "GBP"]),
                    validate.Length(min=1, max=4)
                ]
            )
        )
    
        @validates('currencies')
        def no_duplicate_currencies(self, value):
            if len(value) != len(set(value)):
                raise ValidationError('currencies must not contain duplicate elements')