使用相关表中的值对django QuerySet进行注释 [英] Annotating django QuerySet with values from related table

查看:171
本文介绍了使用相关表中的值对django QuerySet进行注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型页与2个相关模型PageScoreHistory和PageImageHistory,其中两个历史模型都有页面字段作为ForeignKey到页面并且有一个日期字段。我遇到的问题是,当我收到一个PageImageHistory QuerySet的列表时,我想能够检索页面在拍摄图像时的分数。对于一个单独的PageImageHistory对象,我可以轻松地这样做:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆