从ManyRelatedManag返回的筛选器查询集

2024-09-28 16:21:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个“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'))

我想返回一个关于文章的出版物和总读者数的查询,仅适用于数字出版物。在


Tags: in模型model关系models模式languagearticles
1条回答
网友
1楼 · 发布于 2024-09-28 16:21:05

阅读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()
        )
    )
)

相关问题 更多 >