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
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.
The business layer As a rule-of-thumb, your application logic should live in modules that aren't Django-specific modules (eg not in views.py , models.py or forms.py ).
A1: Business Logic goes to Model part in MVC . Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do.
Python Business Logic helps you to add *Business Layer*, also called *Application Layer*, that is dependent only on models and composed of simple functions. Code written this way is extremely easy to read, test, and use in different scenarios.
Business logic is the programming that manages communication between an end user interface and a database. The main components of business logic are business rules and workflows.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With