验证列表元素在棉花糖中是唯一的

Validating list elements are unique in marshmallow

我想了解是否可以使用 marshmallow 验证函数来检查列表中的所有元素是否唯一。

我有以下架构:

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)
            ]
        )
    )

是否有可能保证给定具有重复货币的货币列表 (["USD", "EUR", "EUR"]) 引发 ValidationError

谢谢!

validates decorator 允许自定义验证:

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')

使用 uniqueItems 关键字检查数组元素是否唯一:https://json-schema.org/understanding-json-schema/reference/array.html#id13