Using the prefetch_related() method
The prefetch_related()
method is used as a performance booster on queries pertaining to ManyToManyField
relationships. This method can also be used for ForeignKey
and OneToOneField
relationships and allows for forward and backward lookups, as we will soon practice doing. On the SQL level, this method will generally use a WHERE or INNER JOIN statement to perform lookup operations. Unlike the select_related()
method, the prefetch_related()
method will perform a separate SQL query for each of the related sets of objects. For example, if we looked up a Seller
and wanted the related Vehicles
and their related VehicleModel
and Engine
objects, then Django would perform four separate queries to look up all the related data. To learn more about the prefetch_related()
method in its entirety, visit https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related.
The following are two exercises, related to the vehicles view and the sellers view...