Piotr Niedzwiedz
Piotr Niedzwiedz

Reputation: 323

What kind of methods should be method of model class?

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

Upvotes: 5

Views: 652

Answers (2)

Simon
Simon

Reputation: 715

The standard way in django is to put code that works on table row basis directly in the model, and code that works with several rows, or on table basis, in a manager.

class MyManager(models.Manager):
    def do_something_with_some_rows(self):
        query = self.filter(...)
        result = do_someting_with_this_query(query)
        return result

class MyModel(models.Model):
    objects = MyManager()

then you can use this manager like this

>>> result = MyModel.objects.do_something_with_some_rows()

as rdegges said, this makes your api much cleaner and simpler to use, and it's also a lot easier to test.

https://docs.djangoproject.com/en/dev/topics/db/managers/#managers

Upvotes: 0

rdegges
rdegges

Reputation: 33854

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.

Upvotes: 6

Related Questions