3

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.

2 Answers 2

4

You should be able to use:

App.objects.annotate(release_count=Count('release')).filter(release_count__gt=0)\
    .order_by('-release__date')
Sign up to request clarification or add additional context in comments.

1 Comment

Huh, that's exactly what I was going to do, but I was so SURE it wouldn't work that I never tried it in the interpreter.
2
App.objects \
    .annotate(release_count=Count('release')) \
    .(release_count__gt=0) \
    .order_by('-release_count')

For the bonus part, denormalizing date field looks like the only solution at the moment. And it's pretty fast too.

1 Comment

It's quite simple to order by the release date without denormalizing. See my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.