Skip to content

Instantly share code, notes, and snippets.

@allanlei allanlei/README
Created Jul 18, 2011

Embed
What would you like to do?
Django Custom Queryset Mixin and manager
Based of custom chainable querysets that others have posted + the usage of mixins like the ones found in Django's class based views
Example Queryset:
from django.db import models
class ExchangeQuerySet(models.query.QuerySet):
def my_test(self):
return self.filter()
def tester(self):
return self.filter()
Usage 1:
from queryset import MyQuerySet
from managers import CustomQuerysetManager
class MyModel(models.Model):
objects = CustomQuerysetManager(queryset_class=MyQuerySet)
Usage 2:
from queryset import MyQuerySet
class MyManger(CustomQuerysetMixin, models.Manager):
queryset_class = MyQuerySet
class MyModel(models.Model):
objects = MyManager()
MyModel.objects.my_test()
MyModel.objects.tester()
MyModel.objects.filter(something=something).my_test().tester().tester()
Problems:
I haven't check the cause but it doesn't work on abstract models(abstract=True).
from django.db import models
from queryset import CustomQuerysetMixin
class CustomQuerysetManager(CustomQuerysetMixin, models.Manager):
pass
from django.core.exceptions import ImproperlyConfigured
class CustomQuerysetMixin(object):
queryset_class = None
def __init__(self, *args, **kwargs):
if self.queryset_class is None:
self.queryset_class = kwargs.pop('queryset_class', None)
super(CustomQuerysetMixin, self).__init__(*args, **kwargs)
def get_queryset_class(self):
if self.queryset_class:
qs = self.queryset_class
else:
raise ImproperlyConfigured('Provide queryset_class or override get_queryset_class().')
return qs
def get_query_set(self):
return self.get_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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.