I am performing a custom field-level validation in my serializer that requires referencing another field.
Looking at the examples in the Validation documentation, I'm not clear on whether I should use validate_<fieldname>
or validate
. It looks like both have the attrs
dictionary, so from validate_<fieldname>
I can just as easily reference another field as from validate
(even though the description for validate
indicates that you should use it for accessing multiple fields). So why are there both options? In my case, which option is correct to use?
Raising a ValidationError
inside validate_<foo>()
will result in a field error.
{'foo': ['Not a fooish value.']}
Raising a ValidationError
inside validate()
will result in non-field error.
{'non_field_errors': ['Foo and bar are not compatible.']}
So why are there both options?
Partly because of the above, and partly because the serializer API mirrors Django's form API where possible. There's some differences where needed, but the validate
and validate_<foo>
style is similar.
In my case, which option is correct to use?
You judgement call, based on which error message is more appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With