Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Django

Use of select_related method in Django

4.50/5 (2 votes)
28 Oct 2014CPOL 26.1K  
Query Caching in Django with the help of select_related method

Introduction

select_related is a queryset method in Django which returns new queryset result for a Django Model.

When to use this method?

1. This method is more helpful when we have foreign-key relationships and we are going to use those foreign-key relationship data later in our code.

2. This method is a preformance booster, which caches the result for the foreign-key relationships, so that django don't have to query again to get the data for the foreign-key relationship models.

How it works?

It creates a single complex query joining all the related models and get the data once and caches it for later use, So foreign-key relationships won't require database queries.

Example:

Here is two sample models for illustation

from django.db import models

class Brand(models.Model):
    name = models.CharField(max_length=255, blank=False)

class SubBrand(models.Model):
    name = models.CharField(max_length=255, blank=False)
    brand = models.ForeignKey(Brand)

1. Normal method to get brand informations from subbrand

sub_brand = SubBrand.objects.get(pk=1) ## Hits the database
brand_obj = sub_brand.brand ## Hits the database again

2. using select_related to get brand informations

sub_brand = SubBrand.objects.select_related('brand').get(pk=1) ## Hits the database
brand_obj = sub_brand.brand ## Does not hit the database

In the 2nd example django efficiently fetches data for "brand" and caches it in the first line, so that it doesn't have to query once again to fetch the brand informations.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)