Let's say I have following simplified model:
class CurrentInvoices(models.Manager):
def get_queryset(self):
qs = super(CurrentInvoices, self).get_queryset()
current_invoices = qs.order_by('person', '-created_on').distinct('person').values('pk')
return qs.annotate(invoice_count=models.Count('number')).filter(id__in=current_invoices).order_by('person__last_name')
class Invoice(models.Model):
created_on = models.DateField()
person = models.ForeignKey(Person)
total_amount = models.DecimalField()
number = models.PositiveSmallIntegerField()
objects = models.Manager()
current_invoices = CurrentEDCInvoices()
A Person can have an Invoice
with the same number
if for some reason the previously generated invoice was wrong. The latest one (highest created_on
) is the one that counts.
The trick with .filter(id__in)
in the manager is needed to get the results listed by person
s last name; this cannot be removed.
Now I'd like to annotate the total count of number
.
My try annotate(invoice_count=models.Count('number'))
always returns 1
even though there are multiple.
What am I doing wrong? Any pointers on how to properly achieve this without hacking around too much and without hitting the DB for every invoice?