Click here to Skip to main content
15,891,777 members
Articles / Django
Tip/Trick

Use of select_related method in Django

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
27 Oct 2014CPOL 25.8K   3   1
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)



Comments and Discussions

 
PraiseExplained in a very nice and simple manner! Pin
winter-code25-Sep-20 10:45
winter-code25-Sep-20 10:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.