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:
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...
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With