Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Add Unique validator #1539

Closed
j4k0bk opened this issue Mar 16, 2020 · 4 comments
Closed

Feature request: Add Unique validator #1539

j4k0bk opened this issue Mar 16, 2020 · 4 comments

Comments

@j4k0bk
Copy link

j4k0bk commented Mar 16, 2020

Validates that all values present in a list input is unique, ie. didn't occur more than once.

@tyctor
Copy link

tyctor commented Jun 17, 2020

could be subclass of List or another solution is to use unique=True keyword argument to List field class
and implement code bellow directly into List field

from collections import Counter
from marshmallow.validate import ValidationError

class UniqueList(fields.List):

    default_error_messages = {'unique': 'Values not unique.'}

    def _deserialize(self, value, attr, data, **kwargs) -> typing.List[typing.Any]:
        try:
            result = super()._deserialize(value, attr, data, **kwargs)
        except ValidationError as error:
            raise error
        unique_result = set(result)
        if len(result) > len(unique_result):
            counts = Counter(result)
            unique = list(dict(list(filter(lambda i: i[1] == 1, Counter(result).items()))).keys())
            msg = self.error_messages['unique']
            raise ValidationError(msg, valid_data=unique)
        return result

@sloria
Copy link
Member

sloria commented Jun 17, 2020

Not entirely opposed to adding this, but it's a bit tricky to handle both hashable and non-hashable types. Also, it's pretty easy to define this in userland:

def validate_uniqueness(value: Sequence):
    if len(set(value)) < len(value):
        raise ValidationError("Values must be unique.")

class MySchema(Schema):
    my_field = fields.List(fields.Str(), validate=validate_uniqueness)

I'd recommend doing that for now.

@sloria
Copy link
Member

sloria commented Mar 30, 2021

Closing for now, as we don't have plans to add this to core in the near future and the use case can easily be met in userland (see my comment above)

@sloria sloria closed this as completed Mar 30, 2021
@bonastreyair
Copy link

bonastreyair commented Apr 30, 2021

Check PR #1793 proposal with support for hashable and non-hashable types, as well as the option of adding nested attributes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants