Note that there are some explanatory texts on larger screens.

plurals
  1. POSeparation of business logic and data access in django
    text
    copied!<p>I am writing a project in Django and I see that 80% of the code is in the file <code>models.py</code>. This code is confusing and, after a certain time, I cease to understand what is really happening.</p> <p>Here is what bothers me:</p> <ol> <li>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. </li> <li>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 of <code>User</code>, but technically it should create them uniformly. </li> <li>I do not always notice when the methods and properties of my models become non-deterministic and when they develop side effects.</li> </ol> <p>Here is a simple example. At first, the <code>User</code> model was like this:</p> <pre><code>class User(db.Models): def get_present_name(self): return self.name or 'Anonymous' def activate(self): self.status = 'activated' self.save() </code></pre> <p>Over time, it turned into this:</p> <pre><code>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]) </code></pre> <p>What I want is to separate entities in my code:</p> <ol> <li><strong>Entities of my database, database level: What contains my application?</strong></li> <li><strong>Entities of my application, business logic level: What can make my application?</strong></li> </ol> <p>What are the good practices to implement such an approach that can be applied in Django?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload