#Where to put business logic?

11 messages · Page 1 of 1 (latest)

ornate cedar
#

So I am still getting comfortable with the different parts of Django, but found it difficult to know where to put certain types of logic. It seems like logic relating to models will usually go there, http requests in the view, and data transformation and validation in the serializer (if I were to summarize quickly). I tried researching best practices and one is "Fat models and thin views", but I don't see much on the topic and some people vocalize concerns about models getting too large.

I found a couple of articles that talk about them:
this one as a general overview: https://medium.com/@dev-muhammad/where-to-write-business-logic-in-django-dfe2d13763a3

and this one which is more opinionated: https://emcarrio.medium.com/business-logic-in-a-django-project-a25abc64718c

Anyway, it doesn't seem like an exact science as people seem to have varying opinions, but any advice would be great. I can picture the issues that might arise from putting logic in a place where it is coupled strongly with that part of the code base, but it is hard for me visualize how to prevent it.

Medium

Are you sure that you write business logic Django in right place? Let’s check it.

Medium

Have you ever wondered where in the hello world is your business logic meant to reside in a Django project? In the models, you can argue…

haughty hemlock
#

"Fat Models and Thin Views" sounds good to me, solely because it's easier to test models than views.

#

But don't be religious about it -- if your code a) works and is b) clean, you're fine

sacred jetty
#

Being testable is another good indicator

ornate cedar
#

Thanks!

haughty hemlock
leaden bluff
#

i tend to put business logic in a service.py file or a service/ file

#

a few days ago i came across this article outlining the "layered approach"

#

thats probobly somethign you'd wanna consider if its a large codebase being workon by many teams
as its very different from the django way of doing it (mvt)

cinder iron
#

I'd second abe's suggestion to insert a service layer to help keep business logic out of views/tempates (really important!!) and prevent models from becoming unwieldy. As apps become more complex, I may even break out the service module into a package so services can be logically grouped by responsibility.
This excellent design book also makes a strong recommendation for the "service layer" approach...
https://www.cosmicpython.com/

#

One "trick" I find really improves devX is to define a service class that takes an instance of your model in __init__, then add a property on the Model class to return the default service for an instance. This then provides a clean syntax for accessing the service layer from a model instance:
my_model.service.some_method(..)