Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework: What's really the difference between validate_<fieldname> and validate?

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?

like image 812
Neil Avatar asked Aug 28 '13 07:08

Neil


1 Answers

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.

like image 180
Tom Christie Avatar answered Oct 18 '22 03:10

Tom Christie