Django: Using Annotate, Count and Distinct on a Queryset

后端 未结 2 1176
天涯浪人
天涯浪人 2020-12-11 16:06

Here\'s my database query:

results = Attachments.objects.filter(currency=\'current\').annotate(num_attachments=Count(\'article_id\')).order_by(\"num_attachme         


        
2条回答
  •  伪装坚强ぢ
    2020-12-11 16:50

    I have find another way, how to overcome this - by using a subquery:

    distinct_articles = Attachments.objects.distinct('article_id')
    results = Attachments.objects.filter(currency='current').annotate(num_attachments=Count('article_id')).order_by("num_attachments").filter(id__in=distinct_articles)
    

    This get actually evaluated as one database query in Django.

提交回复
热议问题