Robert Rambles

Share this post

Django’s Select Related is Basically Magic

blog.robertroskam.com

Django’s Select Related is Basically Magic

You Can Seriously Enhance Performance of Django Queries with Select Related

Robert Roskam
Jun 10, 2016
Share this post

Django’s Select Related is Basically Magic

blog.robertroskam.com

You Can Seriously Enhance Performance of Django Queries with Select Related

Sometimes you’ll hit a heavy data webpage, and you’ll see performance absolutely tank. Sometimes — not always — but sometimes the problem is querying against the database.

For instance, let’s consider a list of US counties. You can see very clearly that displaying only the name of County without its State is nonsense. So of course, you write a little display function to show the name of the County and State next to each other. That should be fine, right? (Read the code below to get the context.)

So everything probably seemed fairly normal until you got to the CountyManager. Why do you need that?

If you didn’t have the CountyManager having the select_related method on it, this query would be terribly, terribly slow because it would make 3142 duplicate queries.

I’m going to repeat that: 3142 hits to the database down to 1.

But the cost on me in order to implement the performance tweak is literally seconds.

So if you find a query being very slow, you may want to add some Select Related magic.

Share this post

Django’s Select Related is Basically Magic

blog.robertroskam.com
Comments
TopNew

No posts

Ready for more?

© 2023 Robert Roskam
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing