Skip to content

Instantly share code, notes, and snippets.

@ojii
Created July 3, 2012 13:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ojii/3039684 to your computer and use it in GitHub Desktop.
Save ojii/3039684 to your computer and use it in GitHub Desktop.
Django Model Managers
from django.db import models
class ChainableManager(models.Manager):
"""
A manager that allows chaining of all methods defined on it.
Example:
class MyManager(ChainableManager):
def active(self):
return self.filter(active=True)
def premium(self):
return self.filter(premium=True)
class MyModel(models.Model):
active = models.BooleanField()
premium = models.BooleanField()
objects = MyManager()
active_premium = MyModel.objects.active().premium()
"""
def get_query_set(self):
queryset_class = type('ChainedQuerySet', (QuerySet, self.__class__,), {})
return queryset_class(self.model, using=self._db)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment