Skip to content

Instantly share code, notes, and snippets.

@stefanfoulis
Forked from ojii/chainable_manager.py
Created November 9, 2012 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanfoulis/4045756 to your computer and use it in GitHub Desktop.
Save stefanfoulis/4045756 to your computer and use it in GitHub Desktop.
Django Model Managers
from django.db import models
from django.db.models.query import QuerySet
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