-1

I understand the role of Managers in Django when listing or filtering data. However, when it comes to saving data on the model I often see the following two ways used...

Using a Manager:

class Project(TimeStampedModel):
     stuff

    def save(self, **kwargs):
        Action.objects.log_action(user=self.user,comment="Saves a project")

Not using a Manager:

class Project(TimeStampedModel):
     stuff

    def save(self, **kwargs):
        action = Action(user=self.user,comment="Saves a project")
        action.save

So my question is, given the scenario above which is correct?

Prometheus
  • 32,405
  • 54
  • 166
  • 302

2 Answers2

1

Managers are for class-level stuff. Saving is an instance-level action.

What you are calling save there is actually a create action, which is already provided by default by the Manager class.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • So if Django has ``Model.objects.create()`` they use a manager to save? – Prometheus May 05 '15 at 14:32
  • 1
    when you call [`create()` Queryset method](https://github.com/django/django/blob/1.8c1/django/db/models/query.py#L341-L349) it will call the [`save() Model method `](https://github.com/django/django/blob/1.8c1/django/db/models/base.py#L654-L748) which does the heavy lifting in in table insertion. – Yeo May 05 '15 at 15:00
1

I believed both are fine. However, I prefer to abstract all of the business logic such that we don't even have to know how logging of action is done.

When calling log_action, I am hiding the implementation detail on what should be passed when.

If I didn't use log_action, I might be forgotten that somewhere in my code, I might save the object under different logic.

So back to your question, I believed this is not much of using Manager to save data, but rather how you abstract the business logic.

Yeo
  • 11,416
  • 6
  • 63
  • 90
  • So in the case above you would use the Manager option? – Prometheus May 05 '15 at 14:33
  • 1
    Yes, :-) if you have another models somewhere in your project that require `log_action`, that model have to duplicate the `log_action` logic if you didn't abstract that in the manager.. – Yeo May 05 '15 at 14:52