Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

How to perform SQL LEFT JOIN's using Django

By: a guest on Feb 26th, 2012  |  syntax: None  |  size: 0.97 KB  |  views: 29  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. 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;
  2.        
  3. from project.blog.models import Entry, Comment
  4.  
  5. def index(request):
  6.     latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:15]
  7.     return render_to_response('blog/index.html', {'latest_entry_list': latest_entry_list)
  8.        
  9. from project.blog.models import Entry, Comment
  10.  
  11.   def index(request):
  12.     latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:15]
  13.     latest_entry_list_comment_count = [(x, x.count()) for x in latest_entry_list]
  14.     return render_to_response('blog/index.html', {
  15.          'latest_entry_list': latest_entry_list,
  16. )
  17.        
  18. {% for entry in latest_entry_list %}
  19.     Entry: {{entry.0}}
  20.     Comment count: {{entry.1}}
  21. {% endif %}
clone this paste RAW Paste Data