【问题标题】:filter queryset returned from ManyRelatedManager过滤从 ManyRelatedManager 返回的查询集
【发布时间】:2016-11-29 04:57:39
【问题描述】:

我有一个模型“A”的查询集,我正在尝试对其进行一些值/注释计算。模型“A”与模型 B 具有多对多关系。从模型“A”中,我希望能够基于“B”中的字段访问“B”模型的过滤子集。我将如何更改我的模型“A”以支持这种模式?

虚拟示例:

class Publication(models.Model):
  is_digital = models.BooleanField(default=True)
  readership = models.IntegerField()

class Article(models.Model):
  language = models.CharField()
  published_in = models.ManyToManyField(Publication)

# returns a queryset of {publications: total readership} for the articles
$ articles = Articles.objects.filter(language='en')
$ articles.values('published_in').annotate(Sum('readership'))

我想返回关于文章的出版物和总读者人数的查询仅适用于数字出版物

【问题讨论】:

    标签: python django


    【解决方案1】:

    了解conditional aggregation

    from django.db.models import Sum, Case, When, IntegerField
    
    Article.objects.annotate(
        total_readership=Sum(
            Case(
                When(published_in__is_digital=True, then=1),
                output_field=IntegerField()
            )
        )
    )
    

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 2021-10-21
      • 1970-01-01
      • 2017-12-05
      • 2020-08-05
      相关资源
      最近更新 更多