Created
July 11, 2014 08:05
-
-
Save gchiam/080c536df1289f5f8f98 to your computer and use it in GitHub Desktop.
Django custom model manager chaining
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
"""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