I’m new to Django Annotations and I’m trying to generate a summary report of Order income at given Locations.
For example, the report would look something like this:
Location Name | Location Type | Sum of Order Subtotal
And these are example models that I would use:
class Order(models.Model):
order_subtotal = models.DecimalField(...)
location = models.ForignKey('Location')
....
class Location(models.Model):
name = models.CharField(...)
type = models.IntegerField(...)
....
I’m able to run some queries to annotate…
from django.db import models
In [1]: order_locations =\
Order.objects.values('location').annotate(models.Sum('order_subtotal'))
In [2]: order_locations[0]
Out[2]: {'location': 1, 'order_subtotal__sum': Decimal('1768.08')}
In [3]: location = order_locations[0]['location']
In [4]: location
Out[4]: 1
In [5]: type(location)
Out[5]: <type 'int'>
However, the line above returns an int rather than a Location object. I’d like to be able to somehow reference the location name and location type like location.name or location.type. Is there some way to return a location object in the annotation rather than only the location id (requiring separate potentially expensive lookups)?
Any advice is much appreciated.
Thanks,
Joe
Calculate sum of
order_subtotalfor each location:Calculate sum of
order_subtotalfor each location type:Calculate sum for each location, but don’t include orders older than 14 days::
Also give some attention to: ORDER OF annotate() AND filter() CLAUSES at django docs.