menu

  • Latest Items
  • About Me
  • Projects
  • Blog Archive
  • Links
  • Quotes

Archives

  • Jan 2006
  • Feb 2006
  • May 2006
  • Jun 2006
  • Jul 2006
  • Aug 2006
  • Nov 2006
  • Dec 2006
  • Jan 2007
  • Feb 2007
  • Apr 2007
  • May 2007
  • Jun 2007
  • Jul 2007
  • Aug 2007
  • Sep 2007
  • Oct 2007
  • Nov 2007
  • Dec 2007
  • Jan 2008
  • Feb 2008
  • Mar 2008
  • Apr 2008
  • May 2008
  • Jun 2008
  • Jul 2008
  • Aug 2008
  • Sep 2008
  • Oct 2008
  • Nov 2008

RSS Feeds

  • Latest Items
  • Latest Blog Posts
  • Latest Links
  • Latest Quotes
  • Django-related items

Links

  • atlanta wedding dress
  • A Cincinnati Wedding DJ
  • Ribbon Sheer Ribbon Wholesale
  • Python Programmers and Jobs
  • usa wedding
  • Engagement Rings
  • Custom Rubber Stamps
  • Join our Python Community

GenericForeignKeys with Less Queries

4:53 a.m., Thursday 14 August, 2008. Tagged django, generic, programming and relations

Horst Gutmann from Austria has published this fantastic blog post that gives a great performance boost to Django's generic relationships. In a situation where you have an 'Item' table that has a generic relationship to three sub-tables (eg BlogPost, Photo, Link) when you display details from the sub-tables in a for loop there will be n+1 queries - one query for every item shown.

Horst's trick is to first fetch the content-type ID's in one query, then use one query for each subtable - so 4 queries for the above example, regardless of the number of separate Link or BlogPost items you actually have.

This should do a marvellous job for most tumblog style websites, although I imagine if you had a massive number of items the memory usage would probably spike quite high and you'd be better off having duplicate database queries.

http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/

© Copyright 2008 Ross Poulton. All Rights Reserved. Opinions expressed here are my own, and nare not those of my employer or any other party. Powered by Django.