I have a list of Book objects in Django, and I want admin users to be able to sort them by the number of attached Transations in the past three years.
I can already do this for the number of Transaction objects over all time, using annotate
and a model manager, as below:
class Book(models.Model):
title = models.CharField(max_length=400)
def count(self):
return self.transactioncount/2
count.admin_order_field = 'count'
class Transaction(models.Model):
book = models.ForeignKey(Book)
transaction_date = models.DateTimeField()
class BookManager(models.Manager):
def get_query_set(self):
return super(BookManager,self).get_query_set().annotate(transactioncount=(Count('transaction')))
But I don't know how to do this for transactions in the past three years - I guess I need to rewrite my annotate function, or use something more complex?
Is this even possible in Django?
Many thanks.