Django select_related for all queries


Model with ForeignKey

We will work with these models :

from django.db import models

class Book(models.Model):
 name= models.CharField(max_length=50)
 author = models.ForeignKey(Author)

class Author(models.Model):
 name = models.CharField(max_length=50)

Suppose we often (always) access

In view

We could use the following, each time,

books = Book.objects.select_related('author').all()

But this is not DRY.

Custom Manager

class BookManager(models.Manager):

    def get_queryset(self):
        qs = super().get_queryset()
        return qs.select_related('author')

class Book(models.Model):
    objects = BookManager()

Note : the call to super must be changed for python 2.x

Now all we have to use in views is

books = Book.objects.all()

and no additional queries will be made in template/view.