15👍
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.
3👍
What I’m doing is that most of my apps have service.py
file with business logic. This is because if I need a function that works with models from multiple apps I simply cannot do this:
# shop/models.py
from auth.models import User, Team
This code will be stuck in circular reference loop.
But I’m gonna move most likely from service.py
to app with structure like this:
service/
auth.py
customers.py
another_set_of_functions.py
...
- [Django]-How to serve media files on Django production environment?
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-Timestamp fields in django
0👍
Well the example that you illustrated above with the accountManager.createAccount(account, userList) seems like something that could be easily done my adding a createAccount method to the account model. If you feel the need to take business logic outside of the model though you could always just create a new module that host your business logic, and then import and used in in your views.
- [Django]-Check if celery beat is up and running
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-Is this the right way to do dependency injection in Django?