What methods should be the model class method?

This is a design issue.

Suppose we have a model like this 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 another file called actions.py, and we implement there are other actions. Our task is to determine which methods should be used in models.py, which in actions.py. Do you know a general approach, guide or something like that? I want to use existing solutions as much as possible.

thank

+5
source share
2 answers

A common agreement within MVC (like Django) is to place as much logic as possible in your models. This serves the purpose of:

  • ( ).
  • .
  • , ( ).
  • "" API , : {{ object.price_with_tax }}, .

, models.py, actions.py helpers.py, . , models.py(, - ), helpers.py.

, , .

+6

django , , , , .

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()

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

rdegges, api , .

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

0

All Articles