Django Custom Manager

1.1k Views Asked by At

I'm looking at some code and I'm curious whether this is good practice.

      class ToDoManager(models.Manager):
          def scheduled(self):
          """
          Returns QuerySet of all things to be done.
          """
          return self.filter(...)


      class ImpStuff(models.Model):
          ....model definition

          objects=TodoManager    

I've always seen the custom manager override the get_query_set (paraphrasing) method. Is this a good way to handle things instead?

2

There are 2 best solutions below

1
On BEST ANSWER

i've done this before. it worked fine. so unless you are looking at my code, there are apparently two people in the world that find this useful.

it's not an alternative to overriding get_query_set - it provides additional ways of getting (filtered) instances. you can do both at the same time (within reason).

what problems are you expecting?

PS this approach is also used in Pro Django, page 274 onwards where a Manager is extended with methods like most_recent().

0
On

Using model managers for wrapping complex ORM queries is something very DRY and recommended. You can add parameters to those methods and save yourself a lot of code:

class ToDoManager(models.Manager):
      def scheduled(self, start_date, end_date):
      """
      Returns tasks to be done within two dates.
      """
      return self.filter(...)

Then you just do:

todo_tasks = ImpStuff.objects.scheduled(datetime.now(), datetime.datetime.now() + datetime.timedelta(3))

Managers are used in a lot of open source Django apps, available on Github.