使用相关表中的值对django QuerySet进行注释 [英] Annotating django QuerySet with values from related table
问题描述
pih = PageImageHistory.objects.get(id = 123)
score = pih.page.pagescorehistory_set.filter(datetime__lte = pih.captured).latest('datetime')
但是对于QuerySet,我想避免为集合中的每个成员运行查询。有没有办法这样做是一个理智的方式,没有实际循环遍历集合的所有成员?
没有看到你的模型,但这是否做你想要的?
PageImageHistory.objects.filter(
page__pagescorehistory__datetime__lte = x。捕获
).annotate(Max('page__pagescorehistory__datetime')
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?
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')
这篇关于使用相关表中的值对django QuerySet进行注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!