2016-11-29 61 views
0

我有一個模型「A」的查詢集,我試圖做一些值/註釋計算。模型「A」與模型B具有ManyToMany關係。從模型「A」,我希望能夠基於「B」中的字段訪問「B」模型的過濾子集。我如何改變我的模型「A」來支持這種模式?從ManyRelatedManager返回的過濾器queryset

假例如:

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')) 

我想回出版物和讀者總數的查詢文章僅是數字出版物。

回答

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