Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django. Chain select_related()

this is a simple question:

Does it make sense, or is it possible to chain select_related on a query like this?:

queryset = a.objects.filter(...).select_related("b").select_related("c")

A has a ForeignKey to B, B has a ForeignKey to C. My models look like this:

class A(models.Model):
 b = models.ForeignKey(B)

class B(models.Model):
 c = models.ForeignKey(C)
like image 441
Alejandro Veintimilla Avatar asked Oct 08 '15 17:10

Alejandro Veintimilla


1 Answers

Try this:

queryset = a.objects.filter(...).select_related("b__c")

See the docs

from django.db import models

class City(models.Model):
    # ...
    pass

class Person(models.Model):
    # ...
    hometown = models.ForeignKey(City)

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

and the query:

b = Book.objects.select_related('author__hometown').get(id=4)
p = b.author         # Doesn't hit the database.
c = p.hometown       # Doesn't hit the database.
like image 54
Paulo Pessoa Avatar answered Sep 18 '22 14:09

Paulo Pessoa