Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of methods should be method of model class?

Tags:

python

django

It is design problem.

Let's assume that we have this kind of model in Django:

class Payment(models.Model):
  purchase = ForeignKeyField(Purchase)
  net_price = DecimalField()
  is_accepted = BooleanField()

  def set_accept(self):
    # there will be some logic, which touch purchase, send emails etc.

  def price_with_tax(self):
    return net_price * (1. + TAX)

We have also another file called actions.py and we implement there others actions. Our problem is to determine which kind of methods should be placed in models.py, which in actions.py. Do you know any common approach, guide or something like that? I want to use existing solutions as much as possible.

Thanks

like image 926
Piotr Niedzwiedz Avatar asked Sep 18 '11 20:09

Piotr Niedzwiedz


1 Answers

The overall convention in MVC frameworks (like Django) is to place as much logic as possible into your models. This serves a lot of purposes:

  • It binds your logic to your data (good thing).
  • Makes it easy to look to one place in the code for all data manipulation methods.
  • Allows you to run the methods on your models directly without relying on views (makes testing simpler).
  • Gives you a really 'clean' API to use in your templates, eg: {{ object.price_with_tax }}, as opposed to rendering different views for different behaviors.

For your project layout, you should try to keep any code that works on models in your models.py file, and try to avoid using an actions.py or helpers.py unless you really need it. If you do have long amounts of code that aren't appropriate to put into your models.py (maybe you're implementing algorithms or something), the convention is to use a helpers.py.

There's a lot more stuff you can do later on to keep your app hierarchy clean and organized, but that is the basic gist of it all.

like image 84
rdegges Avatar answered Oct 04 '22 14:10

rdegges