Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Once we find dangerous queries, we should figure out how to reduce them, shouldn't we? We can use two really useful ORM functions to control how extra queries are handled.
.select_related()
and .prefetch_related()
.
Remember the direction each of these goes. select_related
is used on the model when you have the ForeignKey
field. prefetch_related
is used on the model that's related to by the ForeignKey
field.
prefetch_related
won't always reduce the number of queries. It helps to prevent extra queries being run in your templates, though, by fetching and attaching the data before the template is ever rendered.
select_related
, when used correctly, can drastically reduce the number of queries you run.
You need to sign up for Treehouse in order to download course files.
Sign up