Derek Stegelman

Snippet Sunday - Chainable Model Managers for Django

Sunday snippets are bits of code that I’ve found useful in past projects. I post them here in hopes that someone else will find them useful. Most of these are Github Gists and you can follow them there too if you want.

Note: This is now a deprecated way of buildling chainable querysets. Django 1.7 has built in support this type of thing now.

I am always writing managers in Django to handle queries more simply. I always forget how to write them so that they can be chained together. This example is the best I have done, with the smallest amount of code. It seems redundant because you have to repeat the manager methods, but returning a query set allows them to be chained together. Enjoy!

from django.db.models.query import QuerySet
from django.db.models import Manager
from datetime import date


class EventQuerySet(QuerySet):
def published(self):
return self.filter(published=True)

def available_for_adding(self):
return self.filter(published=True, private=False)

def active(self):
return self.filter(event_time__start_date__gte=date.today())

def date_filter(self, start_date, end_date):
return self.filter(event_time__start_date__gte=start_date, event_time__end_date__lte=end_date)


class EventManager(Manager):
def get_query_set(self):
return EventQuerySet(self.model, using=self._db)

def published(self):
return self.get_query_set().published()

def available_for_adding(self):
return self.get_query_set().available_for_adding()

def active(self):
return self.get_query_set().active()

def date_filter(self, start_date, end_date):
return self.get_query_set().date_filter(start_date, end_date)