Разделение бизнес-логики и доступа к данным в Django
Я пишу проект в Django и вижу, что 80% кода находится в файлеmodels.py
, Этот код сбивает с толку, и через некоторое время я перестаю понимать, что на самом деле происходит.
Вот что меня беспокоит:
I find it ugly that my model level (which was supposed to be responsible only for the work with data from a database) is also sending email, walking on API to other services, etc. Also, I find it unacceptable to place business logic in the view, because this way it becomes difficult to control. For example, in my application there are at least three ways to create new instances ofUser
, but technically it should create them uniformly.
I do not always notice when the methods and
properties of my models become non-deterministic and when they develop
side effects.
Вот простой пример. Во-первых,User
модель была такая:
class User(db.Models):
def get_present_name(self):
return self.name or 'Anonymous'
def activate(self):
self.status = 'activated'
self.save()
Со временем это превратилось в это:
class User(db.Models):
def get_present_name(self):
# property became non-deterministic in terms of database
# data is taken from another service by api
return remote_api.request_user_name(self.uid) or 'Anonymous'
def activate(self):
# method now has a side effect (send message to user)
self.status = 'activated'
self.save()
send_mail('Your account is activated!', '…', [self.email])
Я хочу отделить сущности в моем коде:
Entities of my database, database level: What contains my application? Entities of my application, business logic level: What can make my application?Каковы хорошие практики для реализации такого подхода, который может быть применен в Django?