【问题标题】:Count of queryset where foreign key occurs exactly n times外键恰好出现 n 次的查询集计数
【发布时间】:2018-09-20 16:09:33
【问题描述】:

如果我有一个带有外键的 django 模型,例如:

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

有没有办法让我计算在特定日期恰好有 n 篇文章的 reporters 的数量?例如,有多少记者“今天”恰好发表了 2 篇文章

date = timzone.now().date()
articles_on_date = Article.objects.filter(pub_date=date)
# now what can I do?

编辑: 目前我只能通过循环和多次访问数据库来弄清楚如何非常有效地做到这一点。

【问题讨论】:

    标签: django count foreign-keys django-queryset


    【解决方案1】:

    使用条件表达式:

    from django.db import models
    
    Reporter.objects.annotate(
        num_of_articles=models.Count(
            models.Case(models.When(article__pub_date=date, then=1), output_field=models.IntegerField())
        )
    ).filter(num_of_articles=2).count()
    

    【讨论】:

    • 这很有效,而且有点神奇。怎么知道这里对记者的文章进行反向查找?你什么时候做article__pub_date?文章是否成为记者的财产?我以为你必须做类似 article_set 的事情?
    • article_set 用于Reporter 的实例,例如reporter.article_set.filter(pub_date=date)。在您的情况下,您只需使用 Article 模型的小写名称。 article 不是属性,仅用于查询时的查找。
    【解决方案2】:

    试试这个,

    from django.db.models import Count
    
    Article.objects.filter(pub_date=date).values('reporter').annotate(article_count=Count('id')).filter(article_count=2)
    


    这将返回如下列表,
    [{'reporter': 1, 'article_count': 2}]
    1对应reporterreporter实例的id

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 2012-03-04
      • 2013-09-28
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      相关资源
      最近更新 更多