在 Django 的 ORM 中过滤注释或计数

Filtering an annotation or count in Django's ORM

我正在尝试查找至少有 2 个已发布条目的所有博客。

from django.db import models as Count, db_models

class Blog(db_models.Model):
    name = models.CharField(max_length=100)

class Entry(db_models.Model):
    blog = models.ForeignKey(Blog)
    is_published = models.BooleanField()

我可以找到所有至少包含两个条目的博客。

Blog.objects.annotate(entries=Count('entry')).filter(entries__gte=2)

但是我怎样才能从计数中排除所有未发布的条目?

你可以这样试试:

Blog.objects.exclude(entry__is_published=False).annotate(entries=Count('entry')).filter(entries__gte=2)

@ruddra 答案很好,但这样你也会排除具有单个未发布条目和两个以上已发布条目的博客。不幸的是,我能想到的最好的解决方案是使用 django 的 .extra

Blog.objects.extra(
    #the select is optional
    #if u need the blog's published entry count
    select={
        'published_entry_count': "select count(*) from `entry` where `is_published` = 1 and `entry`.`blog_id` = `blog`.`id`"
    },
    where=["(select count(*) from `entry` where `is_published` = 1 and `entry`.`blog_id` = `blog`.`id`) >= 2"]
)