Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually, select_related is what you are looking for. select_related creates a JOIN so that all the data that you need is fetched in one statement. prefetch_related runs all the queries at once then caches them.</p> <p><strong>The trick here is to "join in" only what you absolutely need to in order to reduce the performance penalty of the join.</strong> "What you absolutely need to" is the long way of saying that you should pre-select only the fields that you will read later in your view or template. There is good documentation here: <a href="https://docs.djangoproject.com/en/1.4/ref/models/querysets/#select-related" rel="nofollow">https://docs.djangoproject.com/en/1.4/ref/models/querysets/#select-related</a></p> <p>This is a snippet from one of my models where I faced a similar problem:</p> <pre><code>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(&lt;snip, snip - stuff edited out&gt;) </code></pre> <p>In this pathological case, I went down from 700+ queries to just one. The django debug toolbar is your friend when it comes to this sort of issue.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload