2014-06-06 90 views
3

我有3個模型:論壇,主題,發佈和我正在創建一個視圖來顯示論壇列表。但我也想顯示每個論壇的帖子數量和帖子數量。Django聚合,總數

我接下來要:

  • 計數的職位數爲每個線程
  • 和每個線程的職位數爲每個論壇

我發現類似的東西在這裏:Django: Sum the count of a sub sub foreign object但答案不適合我。

from django.shortcuts import render 
from django.template import Context 
from django.contrib.auth.decorators import login_required 
from django.db.models import Count 

from chinwag.models import Forum, Thread, Post 

@login_required 
def forums(request): 
    forums = Forum.objects.annotate(num_posts=Count('threads__posts')).all(
      ).select_related('threads__last_post') 
    return render(request, 'chinwag/forums.html', Context({ 
     'forums': forums, 
    })) 

是否有可能在1個SQL查詢中執行此操作?怎麼樣?

回答

5

如果我理解正確的話,你可以使用

Forum.objects.annotate(num_threads=Count('threads__id'), 
         num_posts=Count('threads__posts__id')) 

這使得在一個數據庫中命中兩個註解。

第一計數論壇上的所有線程,第二計數論壇上(假設threadForm一個ForeignKey的所有線程的所有帖子和post一個ForeignKeythreads

確切的命名中'threads__posts__id'依賴於外鍵的名稱,但Django會吐出一個錯誤與建議,如果他們是不正確的。

PS你可以刪除.all(),它沒有做任何事情。

+0

謝謝,這就像一個魅力。 :) – valentin