Django: Summing values of records grouped by foreign key

Posted by Dan0 on Stack Overflow See other posts from Stack Overflow or by Dan0
Published on 2010-04-02T10:20:31Z Indexed on 2010/04/02 10:23 UTC
Read the original article Hit count: 544

Hi there

In django, given the following models (slightly simplified), I'm struggling to work out how I would get a view including sums of groups


    class Client(models.Model):
        api_key = models.CharField(unique=True, max_length=250, primary_key=True)
        name = models.CharField(unique=True, max_length=250)

    class Purchase(models.Model):
        purchase_date = models.DateTimeField()
        client = models.ForeignKey(SavedClient, to_field='api_key')
        amount_to_invoice = models.FloatField(null=True)

For a given month, I'd like to see e.g.


April 2010

For Each Client that purchased this month:
*   CLient:  Name
*   Total amount of Purchases for this month
*   Total cost of purchases for this month

 For each Purchase made by client:
  * Date
  * Amount
  * Etc

I've been looking into django annotation, but can't get my head around how to sum values of a field for a particular group over a particular month and send the information to a template as a variable/tag.

Any info would be appreciated

© Stack Overflow or respective owner

Related posts about django

Related posts about django-templates