I see a lot of people mentioning that other ORMs do validation, but not
picking up on a key difference:

Many ORMs are designed as standalone packages. For example, in Python
SQLAlchemy is a standalone DB/ORM package, and other languages have similar
popular ORMs.

But Django's ORM isn't standalone. It's tightly integrated into Django, and
Django is a web framework. And once you focus *specifically* on the web
framework use case, suddenly things start going differently.

For example: data on the web is "stringly-typed" (effectively, since HTTP
doesn't really have data types) and comes in via HTML's form mechanism or
other string-y formats like JSON or XML payloads. So you need not just data
*validation*, but data *conversion* which works for the web use case.

And since the web use case inevitably involves supporting forms/payloads
that don't persist to a relational data store -- think of, for example, a
contact form that sends an email, or forms that store their results
client-side for things like language or theme preferences -- you inevitably
end up needing to do data conversion and validation *independently of the
ORM*.

And at that point, you have to start asking tough questions about whether
it's worth having *two* conversion and validation layers, just because
"every other ORM has this, so we have to put one in the ORM".

Which basically is where Django is. Yes, there are utilities to do your
data conversion and validation in the ORM layer if you want to. But Django
is, first and foremost, a web framework, which needs to support the web use
case I've described above, and so its primary conversion/validation layer
can never be the ORM.

Personally, I wish model-level validation had never been added even as an
option, because in a web framework like Django it's conceptually the wrong
place to put the validation logic. Though that battle was lost many years
ago, I'd be *strongly* against trying to expand it or start forcing the ORM
to default to doing validation work that, in Django, properly belongs to
the forms layer (or to serializers if you use DRF).

So: Django ships with ModelForm, which does the hard work of auto-deriving
as much validation logic as possible from your model definition so you
don't have to repeat it. DRF ships with ModelSerializer, which does the
same thing for its validation/conversion layer. I would strongly urge
people to use them. Trying to force all that validation back into the model
layer misses the bigger picture of what Django is and how it works.

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/CAL13Cg9KHxksNOAVhcOQWS80%2BP5wJbE48V-Z17h15n-krfUVcA%40mail.gmail.com.

Reply via email to