Actually, select_related is what you are looking for. select_related creates a JOIN so that all the data you need is retrieved in a single expression. prefetch_related runs all the requests at once, and then caches them.
The trick here is to βjoinβ what you absolutely need to reduce the penalty for connection performance. βWhat you absolutely needβ is a long way of saying that you should pre-select only the fields that you will read later in your view or template. There is some good documentation here: https://docs.djangoproject.com/en/1.4/ref/models/querysets/#select-related
This is a snippet from one of my models where I ran into a similar problem:
return QuantitativeResult.objects.select_related( 'enrollment__subscription__configuration__analyte', 'enrollment__subscription__unit', 'enrollment__subscription__configuration__analyte__unit', 'enrollment__subscription__lab', 'enrollment__subscription__instrument_model' 'enrollment__subscription__instrument', 'enrollment__subscription__configuration__method', 'enrollment__subscription__configuration__reagent', 'enrollment__subscription__configuration__reagent__manufacturer', 'enrollment__subscription__instrument_model__instrument__manufacturer' ).filter(<snip, snip - stuff edited out>)
In this pathological case, I went down from 700+ requests to one. The django debug toolbar is your friend when it comes to this kind of problem.
source share