Django和条件聚合

Ben*_*end 4 python django aggregate

我有两个模型,作者和文章:

class Author(models.Model):
    name = models.CharField('name', max_length=100)

class Article(models.Model)
    title = models.CharField('title', max_length=100)
    pubdate = models.DateTimeField('publication date')
    authors = models.ManyToManyField(Author)
Run Code Online (Sandbox Code Playgroud)

现在我想选择所有作者并用他们各自的文章计数注释它们.这与Django的聚合物是一块蛋糕.问题是,它应该只计算已发布的文章.根据Django票务跟踪器中的票11305,这还不可能.我试图使用该CountIf票证中提到的注释,但它没有引用日期时间字符串,也没有进行所需的所有连接.

那么,除了编写自定义SQL之外,最好的解决方案是什么?

小智 5

您可以使用受票证11305启发的django-aggregate-if应用程序.或者您可以只使用queryset方法(假设您的应用程序名为"articles"):extra

Author.objects.all().extra(
    select={'article_count': 'SELECT COUNT(*) FROM "articles_article" '
                             'INNER JOIN "articles_article_authors" '
                             'ON "articles_article"."id" = '
                             '   "articles_article_authors"."article_id" '
                             'WHERE "articles_article_authors"."author_id" = '
                             '      "articles_author"."id" '
                             'AND "articles_article"."pubdate" IS NOT NULL'})
Run Code Online (Sandbox Code Playgroud)