Why does Django Rest Framework discourage model level validation?

PythonDjangoSerializationDjango ModelsDjango Rest-Framework

Python Problem Overview


Django Rest Framework serializers do not call the Model.clean when validating model serializers. The explanation given is that this leads to 'cleaner separation of concerns', from the Django Rest Framework 3.0 release notes:

> ## Differences between ModelSerializer validation and ModelForm. > This change also means that we no longer use the .full_clean() method > on model instances, but instead perform all validation explicitly on > the serializer. This gives a cleaner separation, and ensures that > there's no automatic validation behavior on ModelSerializer classes > that can't also be easily replicated on regular Serializer classes.

But what concerns are the authors of Django Rest Framework attempting to separate?


My guess is that they're saying that a model instance should not be concerned about it's own validity. If that's the case I don't understand why.

Python Solutions


Solution 1 - Python

There are two major issues with the model's "full_clean". The first one is technical. There are a couple of cases where the full_clean isn't called at all. For example, you'll bypass it when you do a queryset.update().

The second one is that if you have a complex business logic - which is usually why you'll have a full_clean - it's likely that you should do the validation in the business logic, not go down to the models to validate. Each layer should be responsible for its own consistency and the storage layer - ie models - shouldn't care about the business layer.

Another thing that I can think of is that full_clean will be called once you have a model that comes after the serializer has been doing its validation. At this point, things start getting messy because you have a two-step validation with an object created in between.

If you're using nested serializer, you might be stuck here because you won't be able to create nested models before the primary model has been saved which will make the full clean call even messier - some objects will be created, others will not. It's hard to figure out when and what object should be validated with their full_clean and you can be sure there'll be a lot of complaints from users when they'll override the update/clean and figure out the full_clean hasn't been called for every model. This started becoming a total headache and we prefer to keep things simpler and more explicit.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser916367View Question on Stackoverflow
Solution 1 - PythonLinoviaView Answer on Stackoverflow