I know it's a broad question. But let's imagine you have a Django project with an API used by mobile app clients.
There are many places where you can add validation logic:
save()
methodWhen architecturing your project, what rules/elements help you to choose whether validation should be put here or there?
This is an opinion and style question. I think that that models validation is an absolute requirement, the last defence line against mistakes. Once models validations are in place, you can go on with forms, client and API facing validation.
The specific model validation, fields or model methods (or custom managers etc) is a choice of style, and what works for the specific app, but keep models validation. It's the one place to catch it all. You may have many forms, many APIs, but one point where data goes into the DB.
One of django advantages is that in many cases models validation propagates, e.g. ModelForms. So it's also a convenience, but this is a nice to have: models validation is essentially the last gate to the DB and should be treated properly.
Side note: "fields" validation is actually "DB validation", and "django field validation".
To keep with the DRY principle as much as possible:
Use the django approach of generic validators. So even if you validate in several places, you use the same validation. If this validation changes, it changes everywhere, see https://docs.djangoproject.com/en/1.9/ref/validators/
When possible, all client facing objects should pull the model validations, and use them, or map them to the correct client side validation, similarly to ModelForms.
When possible, use the model validations error messages to create a meaningful feedback to client.
But validations may repeat steps after all, mainly because validation has (at least) two roles: clean the data, and provide feedback to user. The best example is client side validation. It's useful to provide immediate feedback,w/o roundtrip to the server, but it repeats the server side validation. The model validation just makes sure that as you add more forms, API, options, if you forget to implement the correct validation - the model will prevent it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With