In Django, can you add a method to querysets?

Posted by Paul D. Waite on Stack Overflow See other posts from Stack Overflow or by Paul D. Waite
Published on 2011-01-02T01:10:48Z Indexed on 2011/01/02 1:53 UTC
Read the original article Hit count: 541

Filed under:
|

In Django, if I have a model class, e.g.

from django.db import models

class Transaction(models.Model):
    ...

then if I want to add methods to the model, to store reasonably complex filters, I can add a custom model manager, e.g.

class TransactionManager(models.Manager):

    def reasonable_complex_filter(self):
        return self.get_query_set().filter(...)


class Transaction(models.Model):
    objects = TransactionManager()

And then I can do:

>>> Transaction.objects.reasonably_complex_filter()

Is there any way I can add a custom method that can be chained to the end of a query set from the model?

I.e. add the custom method in such a way that I can do this:

>>> Transaction.objects.filter(...).reasonably_complex_filter()

© Stack Overflow or respective owner

Related posts about python

Related posts about django