views:

19

answers:

1

I have a model Page with 2 related models PageScoreHistory and PageImageHistory, where both history models have page field as a ForeignKey to Page and have a date field. The problem I am having, is that when I get a list of PageImageHistory QuerySet, I want to be able to retrieve the score the page had at the time the image was taken. For an individual PageImageHistory object, I can do this easily:

pih = PageImageHistory.objects.get(id=123)
score = pih.page.pagescorehistory_set.filter(datetime__lte=pih.captured).latest('datetime')

But for a QuerySet, I would like to avoid running a query for each member of the set. Is there a wayo to do this is a sane fashion, without actually looping through all members of the set?

A: 

It's hard without seeing your models, but does this do what you want?

PageImageHistory.objects.filter(
    page__pagescorehistory__datetime__lte=x.captured
).annotate(Max('page__pagescorehistory__datetime')
Daniel Roseman
Sorry for the confusion. I had left x when pasting the code. No, this is not what I want. I already have a set of PageImageHistory objects that I want, I don't need to filter it. But just doing annotate(Max('page__pagescorehistory__datetime') will select the most recent datetime from all of score history where I need a most recent score from before the image date.
Mad Wombat
No - it will select the maximum pagescorehistory date that is before x.captured (whatever that is), which is what you requested. See [this bit of the docs](http://docs.djangoproject.com/en/1.2/topics/db/aggregation/#order-of-annotate-and-filter-clauses) for an explanation.
Daniel Roseman