Django aggregation query on related one-to-many objects
Posted
by parxier
on Stack Overflow
See other posts from Stack Overflow
or by parxier
Published on 2010-05-15T06:23:08Z
Indexed on
2010/05/15
6:34 UTC
Read the original article
Hit count: 469
Here is my simplified model:
class Item(models.Model):
pass
class TrackingPoint(models.Model):
item = models.ForeignKey(Item)
created = models.DateField()
data = models.IntegerField()
In many parts of my application I need to retrieve a set of Item
's and annotate each item with data
field from latest TrackingPoint
from each item ordered by created
field. For example, instance i1
of class Item
has 3 TrackingPoint
's:
tp1 = TrackingPoint(item=i1, created=date(2010,5,15), data=23)
tp2 = TrackingPoint(item=i1, created=date(2010,5,14), data=21)
tp3 = TrackingPoint(item=i1, created=date(2010,5,12), data=120)
I need a query to retrieve i1
instance annotated with tp1.data
field value as tp1
is the latest tracking point ordered by created
field. That query should also return Item
's that don't have any TrackingPoint
's at all. If possible I prefer not to use QuerySet
's extra
method to do this.
That's what I tried so far... and failed :(
Item.objects.annotate(max_created=Max('trackingpoint__created'),
data=Avg('trackingpoint__data')).filter(trackingpoint__created=F('max_created'))
Any ideas?
© Stack Overflow or respective owner