Django查询:使用FK对模型实例计数对象数 [英] Django queries: Count number of objects with FK to model instance
问题描述
这应该很容易,但由于某种原因,我无法找到它。我有以下:
应用程序(models.Model):
...
$ b b Release(models.Model):
date = models.DateTimeField()
App = models.ForeignKey(App)
...
如何查询至少有一个版本的所有App对象?
:
App.objects.all()。annotate(release_count = Count('??????'))。 filter(release_count__gt = 0)
这将不起作用,因为Count不跨越关系,至少
最后,我会告诉你, d也喜欢能够按最新发布日期排序Apps。我想在应用程序中缓存最新的发布日期,使它更容易一点(和更便宜),并在Release模型的 save
方法中更新,除非有更好的方法。
编辑:
我使用Django 1.1 - dev预期的1.2如果有一个令人信服的理由,虽然。
您应该能够使用:
App.objects.annotate(release_count = Count('release'))。filter(release_count__gt = 0)\
.order_by(' - release__date')
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)
...
How can I query for all App objects that have at least one Release?
I started typing:
App.objects.all().annotate(release_count=Count('??????')).filter(release_count__gt=0)
Which won't work because Count doesn't span relationships, at least as far as I can tell.
BONUS:
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.
Edit:
I'm using Django 1.1 - not averse to migrating to dev in anticipation of 1.2 if there is a compelling reason though.
You should be able to use:
App.objects.annotate(release_count=Count('release')).filter(release_count__gt=0)\
.order_by('-release__date')
这篇关于Django查询:使用FK对模型实例计数对象数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!