Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 5.08 KB

business_logic.md

File metadata and controls

57 lines (40 loc) · 5.08 KB

Business logic in Django

This is a guide of conventions for storing business logic in Django projects at SoftFormance.

Contents:

Services vs QuerySets/Managers

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

Models/QuerySets/Managers

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.

Useful links