合并两个 Django 查询

Combine two Django queries

我有两个相关模型:

class Category(models.Model):
    pass


class Entry(models.Model):
    category = models.ForeignKey(Category, related_name='entries')
    is_published = models.BooleanField(default=True)

我需要获取已发布条目的类别。

我得到了两个查询:

published = Entry.objects.filter(is_published=True)
categories = Category.objects.filter(entries__in=published)

我可以一次查询完成吗?

使用双下划线进行跨相关对象的查询。

categories = Category.objects.filter(entry__is_published=True)

(请注意,您的原始代码实际上只会执行一个查询,但它会有一个子查询,其效率可能低于我版本中的 JOIN。)