Skip to content

Instantly share code, notes, and snippets.

@jayme-github
Forked from fission6/model_utils.py
Last active August 29, 2015 14:00
Show Gist options
  • Save jayme-github/11282913 to your computer and use it in GitHub Desktop.
Save jayme-github/11282913 to your computer and use it in GitHub Desktop.
from django.db import models
# http://www.djangosnippets.org/snippets/562/#c673
# https://gist.github.com/fission6/2587518
class QuerySetManager(models.Manager):
# http://docs.djangoproject.com/en/dev/topics/db/managers/#using-managers-for-related-object-access
# Only works for OneToOne relations...:
# https://code.djangoproject.com/ticket/14891
use_for_related_fields = True
def __init__(self, qs_class=models.query.QuerySet):
super(QuerySetManager, self).__init__()
self.queryset_class = qs_class
self.custom_methods = [a for a in qs_class.__dict__ if not a.startswith('_')]
def get_queryset(self):
return self.queryset_class(self.model)
def __getattr__(self, attr, *args):
# Allow shallow copy: https://code.djangoproject.com/ticket/15062
if attr in self.custom_methods:
return getattr(self.get_queryset(), attr, *args)
else:
return getattr(self.__class__, 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