When considering performance,
1) Is it better to implement and check a constraint in python/django or in the database? Or possibly both?
2) In django, where is it best to check for constraints? e.g. in the model save function?
Django already implements generic constraints such as primary/foreign key and unique (for single fields or combinations) straight to the database level. For more specific constraints, the best place to put them is inside Django's model validation methods. That way you can take advantage of Django's features such as model inheritance and model forms without having to rewrite your constraint checks in each inherited model or form handling routine respectively.
The performance of your validation methods will be as good as you make it to be. In fact, there can be cases in which you will not have to hit the database, so the performance would likely be better than implementing the same restriction at database level. For example, if you happen to check for some combination of model field values in the object to be saved (not against other saved objects) you do not have to hit the database, but do your checks fast at python object level.
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