
How to perform SQL LEFT JOIN's using Django
By: a guest on
Feb 26th, 2012 | syntax:
None | size: 0.97 KB | hits: 29 | expires: Never
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;
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)
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 %}