Where to put business logic in django

devharb picture devharb · Apr 11, 2011 · Viewed 7.2k times · Source

For example, Account 1--> *User --> 1 Authentication 1 account has multiple users and each user will have 1 authentication

I come from java background so what I usually do is

  1. define these classes as java beans (ie, just getter and setter, no logic attached)
  2. create AccountManager ejb class, define create_account method (with takes 1 account, list of users)
  3. preparing data in the web layer, then pass data into AccountManager ejb, for instance: accountManager.createAccount(account, userList)

But in django, the framework advocates that you put domain logic into model classes (row level) or associated manager classes (table level), which makes things bit awkward. Yes, it is fine that if your logic is only involves one table, but in the real application, usually each step will involve multiple different tables or even databases, so what should I do in this case?

Put the logic into View? I don't think this is good practice at all. or even overwrite the save method in model class, passing in extra data by using **kwargs? then the backend will break.

I hope this illustrates my confusion with where business logic should be placed in a django application.

Answer

Thierry Lam picture Thierry Lam · Apr 11, 2011

Not sure if you've read the section on Managers in Django, it seems to solve your current situation. Assuming you have the following Account model defined, User is built-in.

# accounts/models.py

class AccountManager(models.Manager):
    def create_account(self, account, user_list):
        ...

class Account(models.Model):
    objects = AccountManager()

Feel free to separate your manager code in a separate file if it gets too big. In your views:

# views.py

from accounts.models import Account

Account.objects.create_account(account, user_list)

The business logic is still in the models.

EDIT

The keyword here is override, not overwrite. If you override the model's save method, you have to keep in mind that any create, update operations from within your web app and admin will use this new functionality. If you only want those business logic to happen once in a specific view, it might be best to keep it out of save.

I guess you can put your business logic in its own regular class. You will have to instantiate that class each time you need to run your business logic. Alternatively, you can put your business logic as a static function in this new class if you want to skip the OOP approach.