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 e.g. reasonably complex filters, I can add a custom model manager, e.g.
class TransactionManager(models.Manager):
def reasonably_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()
You need to add methods to the
QuerySetwhich you eventually end up with. So you need to create and use aQuerySetsubclass which has the methods you define wherever you want this functionality.I found this tutorial which explains how to do it and reasons why you might want to:
https://web.archive.org/web/20160329131857/http://adam.gomaa.us/blog/2009/feb/16/subclassing-django-querysets/index.html