Reputation: 2608
I have two related models:
class Category(models.Model):
pass
class Entry(models.Model):
category = models.ForeignKey(Category, related_name='entries')
is_published = models.BooleanField(default=True)
I need to get categories with published entries.
I ended up with two queries:
published = Entry.objects.filter(is_published=True)
categories = Category.objects.filter(entries__in=published)
Can I do this in one query?
Upvotes: 0
Views: 40
Reputation: 599490
Use the double-underscore to make a query across related objects.
categories = Category.objects.filter(entry__is_published=True)
(Note, your original code would actually only do one query, but it would have a subquery which is likely to be less efficient than the JOIN in my version.)
Upvotes: 3