This is a guide of conventions for storing business logic in Django projects at SoftFormance.
Contents:
Weekend hot take: “hide data access behind a service layer” is the “write getter/setter methods wrapping private attributes” of web application architecture.
Which is to say, both can solve niche problems you might not have, but are wrongly promoted as universal best practices.
(c) James Bennett
James Bennett has a good post "Against service layers in Django". Also, there is a followup post "More on service layers in Django".
Comparing where to put business logic in Django you can find that article
Usually, we add methods to our models to encapsulate business logic and hide implementation details. Using low-level ORM code directly in a view is an anti-pattern.
- Make sure you are aware of Manager topic. Pay attention to Default managers and Base managers
- Use only one default Manager
objects
in your model. Django developers are used to thinking of Model.objects as the "gateway" to the table. Here is a showing a different approaches how we can use Managers/QuerySets - Use Proxy model with additional Manager
- Do not modilfy
get_queryset()
unless you understand what you are doing. If you don't completly understand it, then re-read again topic - Start naming of every new queryset method which add annotation with
with
. Example:def with_responses(self):
- Here is a good Django ORM Cookbook with answers to common problems
- Example of design issue in large Django applications
- There was mention of
use_cases.py
module which can be used as a simple layer between Views and Models/Managers/QuerySets.
- Structuring large/complex Django projects, and using a services layer in Django projects
- Building a higher-level query API: the right way to use Django's ORM - comparing different approaches of custom/multiple Managers, custom QuerySet.
- Django models, encapsulation and data integrity - great explanation of rule "fat models, thin views".
- Thin views - what not to put in a view.
- Against service layers in Django - good explain why you don't need "service layer" in Django project
- More on service layers in Django - followup of previous post.
- The Dramatic Benefits of Django Subqueries and Annotations
- Solving Performance Problems in the Django ORM
- Django ORM Cookbook
- Separation of business logic and data access in Django
- Django for Startup Founders: A better software architecture for SaaS startups and consumer apps
- Hacker News: thread about "fat models vs service layers"
- Reddit: Business logic in django
- Medium: Business Logic in Django projects - MUVT - Use cases execute the business logic and run the side effects.
- Django Forum: Where to put business logic in Django?