How to use custom managers in chain queries?
This is how you chain custom methods on custom manager ie: Post.objects.by_author(user=request.user).published()
from django.db.models.query import QuerySetclass PostMixin(object): def by_author(self, user): return self.filter(user=user) def published(self): return self.filter(published__lte=datetime.now())class PostQuerySet(QuerySet, PostMixin): passclass PostManager(models.Manager, PostMixin): def get_query_set(self): return PostQuerySet(self.model, using=self._db)
Link here : django-custom-model-manager-chaining
Note :
In Django 1.7 you have this out of the box . Check out QuerySet.as_manager
Looks like this snippet provides a solution to your situation: Custom managers with chainable filters.
Just a code example using the new as_manager() method (see update information from @zzart.
class MyQuerySet(models.query.QuerySet): def randomize(self): count = self.aggregate(count=Count('id'))['count'] random_index = random.randint(0, count - 1) return self.all()[random_index]class MyModel(models.Model): ..... ..... objects = MyQuerySet.as_manager() ..... .....
And then you will be able to use something like this in your code:
MyModel.objects.filter(age__gt=16).randomize()
As you can see, the new as_manager() is really neat:)