[Answered ]-Django Annoation: Getting Object from Annoation Values Rather than ID

2👍

Calculate sum of order_subtotal for each location:

>>> locations = Location.objects.all().annotate(total=Sum('order__order_subtotal'))
>>> [(loc.name, loc.typ, loc.total) for loc in locations]
[(u'A', 1, Decimal('10.00')),
 (u'B', 1, Decimal('20.00')),
 ...]

Calculate sum of order_subtotal for each location type:

>>> Location.objects.all().values('type').annotate(total=Sum('order__order_subtotal'))
[{'total': Decimal('70.00'), 'typ': 1}, {'total': Decimal('179.00'), 'typ': 2}]

Calculate sum for each location, but don’t include orders older than 14 days::

>>> starting_date = datetime.datetime.now() - datetime.timedelta(14)
>>> locations = Location.objects.filter(order__date_gte=starting_date) \
                                .annotate(total=Sum('order__order_subtotal'))

Also give some attention to: ORDER OF annotate() AND filter() CLAUSES at django docs.

👤Ski

Leave a comment