-
-
Save stefanfoulis/4045756 to your computer and use it in GitHub Desktop.
Django Model Managers
This file contains hidden or 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 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