2009-01-16 198 views
2

基本上我需要每個條目的評論計數:如何使用Django執行SQL LEFT JOIN?

SELECT e.*, COUNT(c.id) as comments FROM blog_entry e LEFT JOIN blog_comment c ON e.id = c.entry_id GROUP BY e.id, e.name, e.name_slug, e.date_published, e.category, e.image, e.body, e.is_published, e.views, e.subscription_sent ORDER BY e.date_published DESC LIMIT 15; 

但我不知道如何去這個使用Django。

這是我到目前爲止,它完美的作品,除了沒有評論計數。有人可以用正確的方向指向我使用Django進行連接嗎?

from project.blog.models import Entry, Comment 

def index(request): 
    latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:15] 
    return render_to_response('blog/index.html', {'latest_entry_list': latest_entry_list) 

回答

1

沒有聚集分支,你可以做返回2tuples名單如下:

from project.blog.models import Entry, Comment 

    def index(request): 
    latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:15] 
    latest_entry_list_comment_count = [(x, x.count()) for x in latest_entry_list] 
    return render_to_response('blog/index.html', { 
     'latest_entry_list': latest_entry_list, 
) 

在您的模板只需使用這樣的:

{% for entry in latest_entry_list %} 
    Entry: {{entry.0}} 
    Comment count: {{entry.1}} 
{% endif %} 
2

如果你不使用主幹Django(因此不能使用新的聚合東西),你可以實現這一點一個傳遞給extra()QuerySet參數的子選擇。額外()的Django文檔使用您想要實現的內容(在選擇標題下)here