Created
May 3, 2012 17:40
-
-
Save fission6/2587518 to your computer and use it in GitHub Desktop.
Chaining Custome QuerySet method for Django Models
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
from django.db import models | |
# http://www.djangosnippets.org/snippets/562/#c673 | |
class QuerySetManager(models.Manager): | |
# http://docs.djangoproject.com/en/dev/topics/db/managers/#using-managers-for-related-object-access | |
# Not working cause of: | |
# http://code.djangoproject.com/ticket/9643 | |
use_for_related_fields = True | |
def __init__(self, qs_class=models.query.QuerySet): | |
self.queryset_class = qs_class | |
super(QuerySetManager, self).__init__() | |
def get_query_set(self): | |
return self.queryset_class(self.model) | |
def __getattr__(self, attr, *args): | |
try: | |
return getattr(self.__class__, attr, *args) | |
except AttributeError: | |
return getattr(self.get_query_set(), attr, *args) | |
class QuerySet(models.query.QuerySet): | |
"""Base QuerySet class for adding custom methods that are made | |
available on both the manager and subsequent cloned QuerySets""" | |
@classmethod | |
def as_manager(cls, ManagerClass=QuerySetManager): | |
return ManagerClass(cls) | |
""" | |
Example | |
class MerchantQuerySet(QuerySet): | |
def live(self): | |
return self.filter(live=True) | |
def locked(self): | |
return self.filter(locked=True) | |
def unlocked(self): | |
return self.filter(locked=False) | |
class Merchant(models.Model): | |
""" | |
""" | |
created_on = models.DateTimeField(auto_now_add=True) | |
modified = models.DateTimeField(auto_now=True) | |
name = models.CharField(max_length=200) | |
live = models.BooleanField(default=False) | |
locked = models.BooleanField(default=True) | |
objects = MerchantQuerySet.as_manager() | |
We can now do | |
Merchant.objects.live().locked() | |
or | |
Merchant.objects.live() | |
or | |
Merchant.objects.live().unlocked() | |
etc ... | |
""" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment