0

I am a newbie to django and was reading about select_related. I understand that whenever a foreign key is accessed django executes an additional query. But when I checked with DEBUG log in my code, it seems django executes two queries no matter if the foreign key is accessed or not. Can someone explain this behaviour ?

class Person(models.Model):
    # ...
    name = models.CharField(max_length=250)

class Book(models.Model):
    # ...
    author = models.ForeignKey(Person, on_delete=models.CASCADE)

As per doc

# Without select_related()...
b = Book.objects.get(id=4)  # Executes a query.
p = b.author         #Executes a query.

But with the get() it executes two queries

b = Book.objects.get(id=4)  # Executes two queries (one for books one for author).

Chandru Jc
  • 105
  • 10

1 Answers1

0

First of all, you need to call select select_related:

ids = [1,2,3,4]
query = Book.objects.filter(id__in=ids).select_related('author')

notice that I did that using the filter method and not the get method.

the reason is that select/prefetch related doesn't work with the get method.

if you still want only one object with select related you should do:

book = Book.objects.filter(id=4).select_related('author')[0]
author = book.author

or do:

book = Book.objects.select_related('author').get(id=4)
author = book.author

if you want to do it for multiple objects and get all the authors:

ids = [1,2,3,4]
query = Book.objects.filter(id__in=ids).select_related('author')
authors_in_query = [book.author for book in query]
yovel cohen
  • 267
  • 3
  • 12