Django queries: Count number of objects with FK to model instance

Posted by Chris Lawlor on Stack Overflow See other posts from Stack Overflow or by Chris Lawlor
Published on 2010-03-18T15:43:17Z Indexed on 2010/03/18 16:11 UTC
Read the original article Hit count: 418

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about django

Related posts about orm