Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC (eg. Django) what's the best place to put your heavy logic?

In MVC architecture lets consider django:

I have a method to calculate best employee of the year (1000 lines of code with a complex logic), where should I define it and who will call it?

Thanks

like image 410
Vishal Avatar asked Nov 11 '09 05:11

Vishal


4 Answers

From the Django docs

Adding extra Manager methods is the preferred way to add "table-level" functionality to your models.

  1. Create a module with that logic (year_employee.py)
  2. Lets say you have a model Employee, so, you should create class for managing employees:

    class EmployeeManager(models.Manager)
        def of_the_year(self):
            from year_employee import my_calc_func
            return my_calc_func()
    

Then add this manager to your model

class Employee(models.Model):
    [...]
    objects = EmployeeManager()

After that you could simply do this:

chosen_employee = Employee.objects.of_the_year()
like image 155
4 revs, 4 users 63% Avatar answered Oct 20 '22 05:10

4 revs, 4 users 63%


As for django, the best place to put business logic is inside models. The view should be clean from business logic and should only be used to get the data to be displayed/presented on template or in other words let the view be used for view logic only.

From django FAQ:

In our interpretation of MVC, the “view” describes the data that gets presented to the user. It’s not necessarily how the data looks, but which data is presented. The view describes which data you see, not how you see it. It’s a subtle distinction.

By putting your business logic under models, it will lead you to unit test easier because models is not coupled with HTTP methods or processing.

like image 40
Joshua Partogi Avatar answered Oct 20 '22 03:10

Joshua Partogi


  1. putting logic in View will not allow you to write unit tests easily and can't reuse effectively.This says that you should never put the complex logic in a view you should separate it from the view.
  2. If logic is closely tied to a (class/objects of a class) putting that logic in the model makes sense.
  3. In case the logic is closely tied multiple objects/classes you can use one of the model to put logic or you can create a service object (or when the code is too huge) which will handle this logic.
like image 28
Rama Vadakattu Avatar answered Oct 20 '22 04:10

Rama Vadakattu


I concur with those who think that such logic should be placed within the models.py files. However, something as big as what you have, with over 1k lines of code, would start to clutter the models.py files [for me]. I would be inclined to move such code in a separate file within a given application. No harm in doing that.

like image 33
ayaz Avatar answered Oct 20 '22 05:10

ayaz