Serializer Field Meta validators

26 views
Skip to first unread message

phi...@futrli.com

unread,
Sep 11, 2017, 6:54:27 AM9/11/17
to Django REST framework
Hi all,

I'm trying to add a list of validators to a subclass of rest_framework.fields.Field.
I would prefer to add the validators to the field declaration, rather than every place it is used.

Ideally, I would like to be able to declare the Field similarly a Serializer, e.g:

class MyField(rest_framework.fields.Field):
    class Meta:
        validators = (
            my_validation_function,
        )

However, it looks like the Meta class is only used in subclasses of Serializer, and not in subclasses of Field.


Adding the validators during __init__ is pretty ugly:

class MyField(rest_framework.fields.Field):
    def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None,
                 label=None, help_text=None, style=None, error_messages=None, validators=None, **kwargs):
        if validators is None:
            validators = []
        else:
            validators = list(validators)
        default_validators = (
            my_validator,
        )
        validators.extend(default_validators)
        super().__init__(read_only, write_only, required, default, initial, source, label, help_text, style,
                         error_messages, validators, **kwargs)


Is there a better way to add a list of validators to a field inside the declaration of the field?

Thanks in advance for any help,
Phil Woods

Xavier Ordoquy

unread,
Sep 11, 2017, 7:02:10 AM9/11/17
to django-res...@googlegroups.com
Hi,

DRF fields adds the validators during the init rather than setting them on Meta.
That help with heritage.


Hope this helps,
Regards,
Xavier Ordoquy,
Linovia.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

phi...@futrli.com

unread,
Sep 11, 2017, 7:29:48 AM9/11/17
to Django REST framework
Aah, I didn't think about updating the validators after calling super().__init__, that's much nicer, thanks!
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages