Using select_related()

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields. It works by performing an SQL JOIN and including the fields of the related object in the SELECT statement.

To take advantage of select_related(), edit the following line of the preceding code:

actions = actions[:10]

Also, add select_related to the fields that you will use, like this:

actions = actions.select_related('user', 'user__profile')[:10]

We use user__profile to join the Profile table in a single SQL ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.