business logic in Django

I don't know why you say

we can't put a lot of logic in the controller, and we cannot have the models with a lot of logic either

You can certainly put logic in either of those places. It depends to a great extent what that logic is: if it's specifically related to a single model class, it should go in the model. If however it's more related to a specific page, it can go in a view.

Alternatively, if it's more general logic that's used in multiple views, you could put it in a separate utility module. Or, you could use class-based views with a superclass that defines the logic, and subclasses which inherit from it.


Having a java background I can relate with this question. I have been working on python for quite some time. Even though I do my best to treat Java as Java and Python as Python, some times I mix them both so that I can get a good deal out of both.

In short

  1. Put all model related stuff in models app, it could be from simply models definition to custom save , pre save hooks .....

  2. Put any request/ response related stuff in views, and some logic like verifying Jon schema, validation request body ... handling exceptions and so on ....

  3. Put your business logic in separate folder/ app or module per views directory/ app. Meaning have separate middle module between your models and views.

There isn't strict rule to organise your code as long as you are consistent.

Project : Ci

  • Models: ci/model/device.py

  • Views: ci/views/list_device.py

  • Business logic:

    • (1) ci/business_logic/discover_device.py

      Or

    • (2) ci/views/discover_device.py

Short answer: Django is more of a MTV or MVT (Model / Template / View), as described in the official FAQ : https://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names

The business logic has its place in your views, but nothing prevents you from putting it inside a "utils.py", "services.py" or anything to your liking.

Tags:

Python

Django