Created
August 22, 2011 09:01
-
-
Save ojii/1161976 to your computer and use it in GitHub Desktop.
ChainableManager for Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.db import models | |
from django.db.models.query import QuerySet | |
class ChainableManager(models.Manager): | |
""" | |
class MyChainableManager(ChainableManager): | |
def active(self): | |
return self.filter(active=True) | |
def inactive(self): | |
return self.filter(active=False) | |
def cool(self): | |
return self.filter(cool=True) | |
def lame(self): | |
return self.filter(cool=False) | |
class MyModel(models.Model): | |
active = models.BooleanField() | |
cool = models.BooleanField() | |
objects = MyChainableManager() | |
MyModel.objects.active().cool() # get all cool active items | |
MyModel.objects.inactive().lame().delete() # delete all inactive-lame items | |
""" | |
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