Django annoyances: no reverse select_related


for page in Page.objects.all():
  print page.title
  for comment in page.comments.all():
    print comment

There will be a single query to fetch all pages, but there will be for every page another query to fetch its comments. Luckily, Django has got a nice trick up its sleave: select_related. Would I use instead of Page.objects.all(), Page.objects.select_related('comments').all() then Django will use a single joined query to prefetch comments for each page.

However, Django’s select_related only supports forward one-to-many references. No many-to-many; certainly no reverce many-to-many; no reverse one-to-many and no, not even reverse one-to-one (yet). A developer claims it’s impossible (which is bullshit), another asks for patches, which means he doesn’t care doing it himself.

It’s quite easy to manually code around the missing reverse select_related, but it takes too many ugly lines compared to the single word it could’ve been.