Skip to content

Instantly share code, notes, and snippets.

@gchiam
Created July 11, 2014 08:05
Show Gist options
  • Save gchiam/080c536df1289f5f8f98 to your computer and use it in GitHub Desktop.
Save gchiam/080c536df1289f5f8f98 to your computer and use it in GitHub Desktop.
Django custom model manager chaining
"""Copied from http://hunterford.me/django-custom-model-manager-chaining/
Reference: http://www.dabapps.com/blog/higher-level-query-api-django-orm/
usage:
Post.objects.published()
Post.objects.by_author(user=request.user).published()
"""
from django.db import models
class PostQuerySetMixin(object):
def by_author(self, user):
return self.filter(user=user)
def published(self):
return self.filter(published__lte=datetime.now())
class PostQuerySet(PostQuerySetMixin, models.query.QuerySet):
pass
class PostManager(PostQuerySetMixin, models.Manager):
def get_query_set(self):
return PostQuerySet(self.model, using=self._db)
class Post(models.Model):
user = models.ForeignKey(User)
published = models.DateTimeField()
objects = PostManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment