简体   繁体   中英

Django - overriding save/delete functions of the model vs doing it in the view

I have a model Quote , which has a foreign key to the user model. A user can have between 0 and 10 quotes, and if there s/he has one or more quotes, one of them should be the primary quote(primary is a field of the Quote model).

When a quote is added by the user, it is checked whether the user has other quotes, if not the new quote is set as the primary. And when the primary quote is deleted another quote is set as the primary quote, if the user has any other quotes.

Right now I do this in the respective views. I was wondering whether it would better to override the save and delete functions of the model and do all of this there.

So which is the right place to perform these tasks the model or the view?

The general consensus is, thick models and helpers, thin views. In other words, your views should be as simple as possible; your models as rich as possible, and plenty of helper code for the outlying bits.

Also keep in mind that if you override the model methods, you are offering a sort of "guarantee" that no matter how the ORM is accessed, your rules will be applied. If you do the logic only in the view, then anywhere else; for example using custom management commands or the django shell, a template tag, or even in another view, there is a chance that your rules will not be applied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM