1

possible refenrece: Separation of business logic and data access in django

In my Django app, I am trying to figure out where to include my business logic. The logic does not fit any models(assume it's a one-page app that doesn't have any models) so I want to add a module that holds the logic. For example,

project/app/my_logic.py

def calculate(number_one, number_two):
  return number_one + number_two

Then, I would use the logic like,

project/app/views.py

def index(request):
  number = my_logic.calculate(1, 2) #can I do this?
  return HttpResponse("the number is: %s " % number)

Questions:

  1. Where is the right place to put my_logic.py?
  2. Is it conventional?
  3. What might be a better way?

Note: this is how you import your module (if anyone else is trying to figure out how to do it)

project/app/your_module/your_module.py
project/app/your_module/__init__.py

from views.py,

from app.your_module import your_module
Community
  • 1
  • 1
Maximus S
  • 10,759
  • 19
  • 75
  • 154

1 Answers1

0

Depends, but if it's a logical unit, then a separate python module would be a good start and you would of course write its own unit tests for it (as opposed to Django's built-in integration tests with TestClient).

If it needs to work within the model, then a property on model would be a better place.

Jure C.
  • 3,013
  • 28
  • 33
  • If I wanted to make it a separate python module, where do I have to place `my_module.py` within the django project directory? – Maximus S Nov 29 '13 at 01:30
  • I would just put it as a new folder inside the app. So app/stats/logic.py. At a later point you could move it to its own python dependency (don't forget to add __init__.py to the folder, so it's importable). – Jure C. Nov 29 '13 at 01:32
  • Then, in `views.py`, I should do `import stats` and use the method like `logic.calculate()`, right? How do I import `stats` package from django shell? – Maximus S Nov 29 '13 at 01:37
  • `Import stats` work, but `stats.my_module.calculate()` raises `module object has no attribute "my_module"` error. – Maximus S Nov 29 '13 at 02:06
  • `from stats import my_module; my_module.calculate()` – Jure C. Nov 29 '13 at 11:55