Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

business logic in Django

Tags:

python

django

I'd like to know where to put code that doesn't belong to a view, I mean, the logic.

I've been reading a few similar posts, but couldn't arrive to a conclusion.

What I could understand is:

  • A View is like a controller, and lot of logic should not put in the controller.
  • Models should not have a lot of logic either.

So where is all the logic based stuff supposed to be?

I'm coming from Groovy/Grails and for example if we need to access the DB or if we have a complex logic, we use services, and then those services are injected into the controllers.

Is it a good practice to have .py files containing things other than Views and Models in Django?

PS: I've read that some people use a services.py, but then other people say this is a bad practice, so I'm a little confused...

like image 732
nelson687 Avatar asked Jan 27 '14 10:01

nelson687


People also ask

What is business logic in Django?

The django-business-logic library tries to utilise the block programming approach to delegate programming tasks to non-programmers by implementing a framework for creating and working with Visual Domain Specific Languages. The library comes with: pretty easy integration: minor changes in INSTALLED_APPS and root urlconf.

Where should the business logic in Django be?

Daniel Greenfeld, co-author of "Two Scoops of Django, recommends the business logic should be in the models "when possible, or in the forms if you must." As for Bart's possible duplicate, django may be similar to MVC but it is not MVC.

What is business logic in Python?

Python Business Logic helps you to add *Business Layer*, also called *Application Layer*, that is dependent only on models and composed of simple functions. Code written this way is extremely easy to read, test, and use in different scenarios.

What is an example of business logic?

Many financial organizations rely on business logic to define how a business system or application performs calculations and executes a transaction. For example, when you make a website purchase, business logic determines things like how much you should pay for shipping or taxes before providing you with a final total.


1 Answers

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.

like image 108
Daniel Roseman Avatar answered Sep 28 '22 06:09

Daniel Roseman