WHERE TO PLACE BUSINESS LOGIC IN DJANGOS' MTV

69 views
Skip to first unread message

Eddilbert Macharia

unread,
Sep 7, 2014, 3:26:13 AM9/7/14
to django...@googlegroups.com
Hi All,

I have been to post like this https://groups.google.com/forum/#!topic/django-users/Ykppb4uELJ4 and other places and i'm even more confused than when i started.

Where should the business logic be placed in django, and what should go where in the following suggestions below ?

i'm aware of the following suggestions of placing the business logic:
  1.  in the model.py module as custom methods to models to be used in the instances of the model, this i have seen that using the http request and response is a security issue.also placing this business logic here makes this module extreme big.
  2.  custom managers the manager affects the entire database table of the specified model,
  3.  separate module to hold the business logic e.g service.py,

What i have seen in complete unity from the posts is that the business logic should not be in the view.py module, as of my understanding its supposed to handle http requests and response and delegating templates to use.also it becomes hard to do unit testing.

Regards,
Eddilbert Macharia.

Derek

unread,
Sep 8, 2014, 3:04:22 AM9/8/14
to django...@googlegroups.com
There are many more wise heads than me ... so I can only report on what many others have said.

"Fat Models, Helper Modules, Thin Views, Stupid Templates" i.e Put more logic into anything but views and templates;
Template tags and filters should contain the minimum logic possible (http://slidedeck.io/accavdar/DjangoBestPractices)


In reply to your issues:

1. What has size to do with it?  Split them up into different sub-files if you need to keep things short & then "import" them into the models file.

2. Custom managers are essentially fancy "filters" and not business logic - keep them short, focused and to-the-point.

3. Yes; if appropriate for your case i.e. you need logic shared across multiple places in your app/project (see also the stackexchange answer).

(4) Unit testing is a whole other story.  But there is nothing particularly weird or obscure in this approach that could not be tested.

Finally, remember the Zen of Python:

If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.

HTH
Derek
Reply all
Reply to author
Forward
0 new messages