Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It seems like you are asking about the difference between the <em>data model</em> and the <em>domain model</em> – the latter is where you can find the business logic and entities as perceived by your end user, the former is where you actually store your data. </p> <p>Furthermore, I've interpreted the 3rd part of your question as: how to notice failure to keep these models separate. </p> <p>These are two very different concepts and it's always hard to keep them separate. However, there are some common patterns and tools that can be used for this purpose. </p> <h2>About the Domain Model</h2> <p>The first thing you need to recognize is that your domain model is not really about data; it is about <em>actions</em> and <em>questions</em> such as "activate this user", "deactivate this user", "which users are currently activated?", and "what is this user's name?". In classical terms: it's about <em>queries</em> and <em>commands</em>. </p> <h2>Thinking in Commands</h2> <p>Let's start by looking at the commands in your example: "activate this user" and "deactivate this user". The nice thing about commands is that they can easily be expressed by small given-when-then scenario's: </p> <blockquote> <p><strong>given</strong> an inactive user <br/> <strong>when</strong> the admin activates this user <br/> <strong>then</strong> the user becomes active <br/> <strong>and</strong> a confirmation e-mail is sent to the user <br/> <strong>and</strong> an entry is added to the system log<br/> (etc. etc.)</p> </blockquote> <p>Such scenario's are useful to see how different parts of your infrastructure can be affected by a single command – in this case your database (some kind of 'active' flag), your mail server, your system log, etc. </p> <p>Such scenario's also really help you in setting up a Test Driven Development environment. </p> <p>And finally, thinking in commands really helps you create a task-oriented application. Your users will appreciate this :-)</p> <h2>Expressing Commands</h2> <p>Django provides two easy ways of expressing commands; they are both valid options and it is not unusual to mix the two approaches. </p> <h3>The service layer</h3> <p>The <em>service module</em> has already been <a href="https://stackoverflow.com/a/12579490/383793">described by @Hedde</a>. Here you define a separate module and each command is represented as a function. </p> <p><strong>services.py</strong></p> <pre><code>def activate_user(user_id): user = User.objects.get(pk=user_id) # set active flag user.active = True user.save() # mail user send_mail(...) # etc etc </code></pre> <h3>Using forms</h3> <p>The other way is to use a Django Form for each command. I prefer this approach, because it combines multiple closely related aspects:</p> <ul> <li>execution of the command (what does it do?)</li> <li>validation of the command parameters (can it do this?)</li> <li>presentation of the command (how can I do this?)</li> </ul> <p><strong>forms.py</strong></p> <pre><code>class ActivateUserForm(forms.Form): user_id = IntegerField(widget = UsernameSelectWidget, verbose_name="Select a user to activate") # the username select widget is not a standard Django widget, I just made it up def clean_user_id(self): user_id = self.cleaned_data['user_id'] if User.objects.get(pk=user_id).active: raise ValidationError("This user cannot be activated") # you can also check authorizations etc. return user_id def execute(self): """ This is not a standard method in the forms API; it is intended to replace the 'extract-data-from-form-in-view-and-do-stuff' pattern by a more testable pattern. """ user_id = self.cleaned_data['user_id'] user = User.objects.get(pk=user_id) # set active flag user.active = True user.save() # mail user send_mail(...) # etc etc </code></pre> <h2>Thinking in Queries</h2> <p>You example did not contain any queries, so I took the liberty of making up a few useful queries. I prefer to use the term "question", but queries is the classical terminology. Interesting queries are: "What is the name of this user?", "Can this user log in?", "Show me a list of deactivated users", and "What is the geographical distribution of deactivated users?" </p> <p>Before embarking on answering these queries, you should always ask yourself two questions: is this a <em>presentational</em> query just for my templates, and/or a <em>business logic</em> query tied to executing my commands, and/or a <em>reporting</em> query. </p> <p>Presentational queries are merely made to improve the user interface. The answers to business logic queries directly affect the execution of your commands. Reporting queries are merely for analytical purposes and have looser time constraints. These categories are not mutually exclusive. </p> <p>The other question is: "do I have complete control over the answers?" For example, when querying the user's name (in this context) we do not have any control over the outcome, because we rely on an external API. </p> <h2>Making Queries</h2> <p>The most basic query in Django is the use of the Manager object: </p> <pre><code>User.objects.filter(active=True) </code></pre> <p>Of course, this only works if the data is actually represented in your data model. This is not always the case. In those cases, you can consider the options below. </p> <h3>Custom tags and filters</h3> <p>The first alternative is useful for queries that are merely presentational: custom tags and template filters. </p> <p><strong>template.html</strong></p> <pre><code>&lt;h1&gt;Welcome, {{ user|friendly_name }}&lt;/h1&gt; </code></pre> <p><strong>template_tags.py</strong></p> <pre><code>@register.filter def friendly_name(user): return remote_api.get_cached_name(user.id) </code></pre> <h3>Query methods</h3> <p>If your query is not merely presentational, you could add queries to your <strong>services.py</strong> (if you are using that), or introduce a <strong>queries.py</strong> module: </p> <p><strong>queries.py</strong></p> <pre><code>def inactive_users(): return User.objects.filter(active=False) def users_called_publysher(): for user in User.objects.all(): if remote_api.get_cached_name(user.id) == "publysher": yield user </code></pre> <h3>Proxy models</h3> <p>Proxy models are very useful in the context of business logic and reporting. You basically define an enhanced subset of your model. You can override a Manager’s base QuerySet by overriding the <a href="https://docs.djangoproject.com/en/2.0/topics/db/managers/#modifying-a-manager-s-initial-queryset" rel="noreferrer"><code>Manager.get_queryset()</code></a> method. </p> <p><strong>models.py</strong></p> <pre><code>class InactiveUserManager(models.Manager): def get_queryset(self): query_set = super(InactiveUserManager, self).get_queryset() return query_set.filter(active=False) class InactiveUser(User): """ &gt;&gt;&gt; for user in InactiveUser.objects.all(): … assert user.active is False """ objects = InactiveUserManager() class Meta: proxy = True </code></pre> <h3>Query models</h3> <p>For queries that are inherently complex, but are executed quite often, there is the possibility of query models. A query model is a form of denormalization where relevant data for a single query is stored in a separate model. The trick of course is to keep the denormalized model in sync with the primary model. Query models can only be used if changes are entirely under your control. </p> <p><strong>models.py</strong></p> <pre><code>class InactiveUserDistribution(models.Model): country = CharField(max_length=200) inactive_user_count = IntegerField(default=0) </code></pre> <p>The first option is to update these models in your commands. This is very useful if these models are only changed by one or two commands. </p> <p><strong>forms.py</strong></p> <pre><code>class ActivateUserForm(forms.Form): # see above def execute(self): # see above query_model = InactiveUserDistribution.objects.get_or_create(country=user.country) query_model.inactive_user_count -= 1 query_model.save() </code></pre> <p>A better option would be to use custom signals. These signals are of course emitted by your commands. Signals have the advantage that you can keep multiple query models in sync with your original model. Furthermore, signal processing can be offloaded to background tasks, using Celery or similar frameworks. </p> <p><strong>signals.py</strong></p> <pre><code>user_activated = Signal(providing_args = ['user']) user_deactivated = Signal(providing_args = ['user']) </code></pre> <p><strong>forms.py</strong></p> <pre><code>class ActivateUserForm(forms.Form): # see above def execute(self): # see above user_activated.send_robust(sender=self, user=user) </code></pre> <p><strong>models.py</strong></p> <pre><code>class InactiveUserDistribution(models.Model): # see above @receiver(user_activated) def on_user_activated(sender, **kwargs): user = kwargs['user'] query_model = InactiveUserDistribution.objects.get_or_create(country=user.country) query_model.inactive_user_count -= 1 query_model.save() </code></pre> <h2>Keeping it clean</h2> <p>When using this approach, it becomes ridiculously easy to determine if your code stays clean. Just follow these guidelines:</p> <ul> <li>Does my model contain methods that do more than managing database state? You should extract a command. </li> <li>Does my model contain properties that do not map to database fields? You should extract a query. </li> <li>Does my model reference infrastructure that is not my database (such as mail)? You should extract a command.</li> </ul> <p>The same goes for views (because views often suffer from the same problem). </p> <ul> <li>Does my view actively manage database models? You should extract a command.</li> </ul> <h2>Some References</h2> <p><a href="https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models" rel="noreferrer">Django documentation: proxy models</a></p> <p><a href="https://docs.djangoproject.com/en/dev/topics/signals/" rel="noreferrer">Django documentation: signals</a></p> <p><a href="https://rads.stackoverflow.com/amzn/click/0321125215" rel="noreferrer">Architecture: Domain Driven Design</a></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