Django's select_related and prefetch_related

I was working on a personal website for my kids where I can post videos for them and I noticed that for each video link that was displayed on the page there were 2 additional SQL queries. One to get the username of the user that added the video link, and another to get the list of categories for the link.

The model looks like this:

class Link(models.Model):
    ...
    # There was an extra query per link to get the categories for a link
    category = models.ManyToManyField(Category)
    # There was an extra query per link to get the user.username
    user = models.ForeignKey(User)
    ...

The reason that an extra query was required to get the username is because the query to get all the links does not look at the user table at all. It doesn't do any joins. So it has to look up the username by doing something like "select username from users where users.pk == link.user_id". You get the idea. And it has to do this for every link on the page. This is easily fixed by doing

Link.objects.select_related().all()

or something similar. Django will then do a JOIN on the User table so it will now have all the user-related fields in the result set.

I was still getting a query for the category names on each link. To resolve this, I did:

Link.objects.select_related().all().prefetch_related('category')

This causes Django to do a fetch on the Category_Link table (the table that describes the many-to-many relationship) to get all the categories that match the primary keys for the links displayed on the current page. Then a join is done in Python, essentially mapping a list of category objects with each link object.

The number of queries for my home page was reduced from 44 down to 5. Page load time has been decreased by 1-2 orders of magnitude.

So, the naive rule-of-thumb might be to always use select_related() if you have a ForeignKey and you are going to reference fields in the ForeignKey in your template, and to always use prefetch_related if you have a ManyToManyField and you need information in the related table. For now I am going to NOT use these commands unless I first use the django-debug-toolbar and figure out what is going on. Then if it's necessary to use select_related or prefetch_related I will.

Tags: 

Comments

I then removed the memory once more and also added my remote and also my spouse's
remote as well as it took them both as well as they functioned.
Playboy TELEVISION, Truth Kings Television, Genuine, fresh!, Juicy are the grown-up channels offered in both Recipe Network and DirecTV with very same programming.

Meal Network offers these grown-up channels for $13.99 whereas DirecTV provides much less than Recipe
Network ie $10.99. Hustler TV in Recipe Network allows subscribers to experience the adult programs in both HD as well as SD.
On the other hand, in DirecTV Hustler TELEVISION can be enjoyed only in SD.

Xtsy is an adult channel that delivers adult motion pictures without censor is available
in Dish Network as well as not readily available in DirecTV.
Ok, as soon as gotten rid of, you take each remote control, and most likely to
the back of the opener where the learn switch is. Hold the remote control switch down, and also push and also
launch the discover button.

You don't have to schedule any tables or stand in any type
of lines, you don't need to stress over resting alongside a person eating cheese snacks at the motion pictures,
and also you don't should worry about sitting alongside a loud couple at a classy restaurant
- destroying your concept of an enchanting night out. showers|showers
I believe bathing during the night is best b/c you get up, shower (which I
settle on you do get dirty a couple of humans resources later on), you sweat throughout the day and also yes there are bacteria
everywhere!

Grownup - DISH Network and DIRECTV offer adult programs from Playboy TELEVISION,
Grown-up Display, Seasoning Ultimate, and also others, but you must be 18 or older to purchase
these networks. Since you've got every one of your terminals configured for Program
A, make use of the Program button to transfer to Program B.
Repeat the process of setting your station run times
but include 5 to 7 minutes to the setup you used for
Program A. So if you set a spray area in Program A to 7
minutes, set that very same spray area to someplace around 12 to 14 mins.

Unquestionably believe that which you said.
Your favorite justification seemed to be on the internet
the easiest thing to be aware of. I say to you, I certainly get
irked while people consider worries that they just don't
know about. You managed to hit the nail upon the top and defined out the
whole thing without having side-effects , people could
take a signal. Will probably be back to get more. Thanks

Wonderful goods from you, man. I have understand your stuff previous
to and you are just too wonderful. I actually like what you've acquired here, really like what you're stating and the way in which you
say it. You make it enjoyable and you still take care of
to keep it wise. I can't wait to read much more from you.
This is really a terrific web site.

My web page ... extract contains (Brenda)

I think everything wrote made a lot of sense. However,
consider this, suppose you typed a catchier post title?
I am not saying your content isn't good., however what if you added a title that makes people desire more?
I mean Add new comment | David Grant is a little vanilla.
You might look at Yahoo's front page and note how they create news headlines to grab people to click.
You might try adding a video or a related pic or two to get readers interested about what you've got to say.
Just my opinion, it could bring your website a little livelier.

How do they do it? every business enterprise is exceptional and makes use of its personal set of strategies and strategies to deliver fans and likes. In our opinions, we state every business enterprise’s strategies. AutoLikesig

We have been here ѕhowinbg you ԝaays to complete WWE Chajpions hаck for gеtting endless Cash and
Coins you andropid and iOS video gaming for without having to pay anything.
WWE Chamіons game that is definitely mosst Popular gаme
about the tem right this moment. Many peoplee play WWE Chаmρions game on eveгy іOSand android game.
WWE Champikons game have lots off cօmpetition over the
internet to rank up game fast. Εveryone loⲟking these
day wayy hack WWE Champions gɑme and aadd endless game resources like Cash and Coins.
WᎳE Champiions cheats will be worth to do,
or else you have to buy WWE Champions Caѕh and Coins ⲟn anytime you want to elp the game.
Using WWE Champions Mods the right solution іs in the situatin to have just
as muuch as you would like basically unlimited
Cash ɑnd Coins. Learning hack isn't bad thing.

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.
italian shoes for ladies

I do believe all of the ideas you have offered to your post.
They're very convincing and will certainly work.

Still, the posts are very short for beginners. May you please
lengthen them a little from subsequent time? Thanks for
the post.

I experience considerable difficulties my considerations on substance, however I truly felt I ought to here. Your article is truly awesome. I like the way you composed this data. kit tattoo

It was a decent post undoubtedly. I completely delighted in understanding it in my lunch time. Will most likely come and visit this blog all the more regularly. A debt of gratitude is in order for sharing. taxi from delhi to jaipur

Thanks for the great article! I'm looking at investing in a camera for my vacation I'll be taking next month and this is useful!
download lagu terbaru

POWERFUL SEARCH- Powerful Search engine for address, point of interest or near you. download pdf Please note:In the free version of this app you can only control up to two lights at the same time.

Add new comment