Tuesday, November 30, 2010

Adding extra data in annotate()

All,

I'm attempting to consolidate many orm queries into one. My models:

class Key (models.Model):
name = models.CharField()

class Value (models.Model):
data = models.FloatField()
timestamp = models.DateTimeField()
key = models.ForeignKey(Key)

Given a list of Key names, I am able to annotate the count of Value
objects associated. However, I would also like to construct a query
that will take a list of Key names and find an aggregate (Min, Max)
Value with additional annotations (timestamp).

Currently, it's an inefficient loop:

>>> # Simulate input parameters.
>>> key_names = ["key 1", "key 2", "key 3"]
>>> end = datetime.datetime.now()
>>> start = end - datetime.timedelta(days=-1)
>>>
>>> # output dict.
>>> lasts = {}
>>>
>>> for key_name in key_names:
... # Narrow down the Value objects by key name.
... qs = Value._default_manager.filter(key__name=key_name)
... # And by date range.
... qs = qs.filter(value__timestamp__range=(start, end))
... # Find the most recent timestamp.
... last = qs.aggregate(last=Max("timestamp"))["last"]
... # With the most recent timestamp, filter the queryset for
the matching record.
... value = qs.filter(timestamp=last)[0]
... # Append to output
... lasts[key_name] = {"timestamp" : value.timestamp, "data" :
value.data}
>>> lasts

Is there a more efficient way to aggregate and/or annotate all of the
latest Value data and timestamp object fields onto the associated Key
object?

TIA

Franco

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment