~ 1 min

How to keep business logic out of the views in django?

If you look around, you'll find many references telling you to keep your business logic out of your views. This seems reasonable and by providing an example, those resources will explain this in a way that it makes total sense, at least at the time. Sadly, since your project is probably very different than the example, once you want to organize your code, you start having some doubts and you have no idea where to put everything.

Organization
Barn Images by barnimages [source]

The next time you want to split that 200 lines view function, start by identifying the main logic blocks of the function. Stuff like: fetching the data from the database, validating inputs from the users (never thrust them!), formatting data before rendering it, ...

If you have trouble identifying the blocks, think about how would you write tests to validate those blocks in a simple way. By doing so, your logic will tend to become simpler and more composable.


Now for each block you identified:

  • If the logic of the block is applied to a single instance of an single model, then it should be a method or attribute directly on that model;

  • If the logic is applied to more than instance of a single model, also known as queryset, keep it in a model manager;

  • If it applies to different models (or none), store the business logic into a file called services.py or helpers.py in the appropriate app;

  • If it applies different models (or none) of different apps, store it in a services.py/helpers.py in the project's root. You can also create an separate app to store business logic that touches more than app at once.

Instead of providing some example, in providing this "reasoning" guide, I hope you can apply this more easily to your project.

Subscribe to the newsletter

As a full-stack web developer I write about both the backend and frontend. If you liked what you read and want more, subscribe to my newsletter and I'll be sure to let you know once I release new articles.

I hope you like it! Share it with others who could enjoy it too.

Related posts

If you liked this post and want to read more, take a loot at these: