Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to check for constraints, in django or database?

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?

like image 705
Derek Avatar asked Jul 07 '13 08:07

Derek


1 Answers

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.

like image 100
Ernest0x Avatar answered Oct 22 '22 20:10

Ernest0x