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

I am doing field level custom checking in my serializer, which requires a reference to another field.

Looking at the examples in the Validation Documentation , I don’t understand whether validate_<fieldname> or validate should be used. Both seem to have an attrs dictionary, so from validate_<fieldname> I can just as easily reference another field as validate (although the description for validate means you have to use it to access multiple fields). So why are there both options? In my case, which option is the right one to use?

+6
source share
1 answer

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 an error other than a field.

 {'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, where possible, reflects the Django API. There are differences somewhere, but the validate and validate_<foo> styles are similar.

In my case, which option is the right one to use?

You make a decision based on which error message is more appropriate.

+17
source

Source: https://habr.com/ru/post/952641/


All Articles