Django 查询:使用 FK 计算对象的数量以建模实例 [英] Django queries: Count number of objects with FK to model instance

查看:26
本文介绍了Django 查询:使用 FK 计算对象的数量以建模实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很容易,但由于某种原因我找不到它.我有以下内容:

This should be easy but for some reason I'm having trouble finding it. I have the following:

App(models.Model):
    ...

Release(models.Model):
    date = models.DateTimeField()
    App = models.ForeignKey(App)
    ...

如何查询至少有一个 Release 的所有 App 对象?

How can I query for all App objects that have at least one Release?

我开始打字了:

App.objects.all().annotate(release_count=Count('??????')).filter(release_count__gt=0)

这不起作用,因为 Count 不跨越关系,至少据我所知.

Which won't work because Count doesn't span relationships, at least as far as I can tell.

奖励:

最后,我还希望能够按最新发布日期对应用程序进行排序.我正在考虑在应用程序中缓存最新的发布日期以使其更容易(并且更便宜),并在发布模型的 save 方法中更新它,除非当然有更好的方法.

Ultimately, I'd also like to be able to sort Apps by latest release date. I'm thinking of caching the latest release date in the app to make this a little easier (and cheaper), and updating it in the Release model's save method, unless of course there is a better way.

我正在使用 Django 1.1 - 如果有令人信服的理由,我不反对在预期 1.2 的情况下迁移到 dev.

I'm using Django 1.1 - not averse to migrating to dev in anticipation of 1.2 if there is a compelling reason though.

推荐答案

你应该可以使用:

App.objects.annotate(release_count=Count('release')).filter(release_count__gt=0)
    .order_by('-release__date')

这篇关于Django 查询:使用 FK 计算对象的数量以建模实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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