Why does Django Rest Framework discourage model le

2019-02-02 21:53发布

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.

1条回答
Emotional °昔
2楼-- · 2019-02-02 22:11

There are two major issues with model's "full_clean". The first one is technical. There are a couple of cases where the full_clean isn't call 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 of its own consistence 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 which 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 creation 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 more messy - some objects will be created, other 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 complains from users when they'll override the update/clean and figure out the full_clean hasn't been called for every models. This start becoming a total headache and we prefer to keep things simpler and more explicit.

查看更多
登录 后发表回答