Created
August 8, 2011 21:48
-
-
Save vbmendes/1132844 to your computer and use it in GitHub Desktop.
Django Manager to improve querysets usage
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 | |
# based on 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 | |
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) |
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 | |
from query import QuerySet | |
class CustomQuerySet(QuerySet): | |
def published(self): | |
return self.filter(published=True) | |
class Content(models.Model): | |
manager = CustomQuerySet.as_manager() | |
published = models.BooleanField() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment