Tag generic
GenericForeignKeys with Less Queries
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/