elasticsearch-dsl-py icon indicating copy to clipboard operation
elasticsearch-dsl-py copied to clipboard

add choices to Field

Open andreip opened this issue 7 years ago • 2 comments

What do you think about supporting some choices per Field class? Similar to required, it would only be validated by the library, ES not having support built-in.

I'm thinking it's easy to support it, just add the logic in the clean method on Field? But I don't really know how you'd make it unsupported for fields where it doesn't make sense, like Boolean, possibly Text?

I used below code to make myself a Keyword accepting choices, but that could go inside Field directly I think.


class ChoicesKeyword(Keyword):
    def __init__(self, *args, **kwargs):
        self._choices = kwargs.pop('choices', ())
        super(ChoicesKeyword, self).__init__(*args, **kwargs)

    def clean(self, data):
        data = super(ChoicesKeyword, self).clean(data)
        if self._choices:
            if isinstance(data, list):
                for choice in data:
                    self.validate_choice(choice, self._choices)
            else:
                self.validate_choice(data, self._choices)
        return data

    def validate_choice(self, choice, choices):
        if choices and choice not in choices:
            raise ValidationException("Choice %r not in allowed choices %r." % (
                                      choice, self._choices))

andreip avatar Dec 08 '17 12:12 andreip