Django Select_related () chain

This is a simple question:

Does it make sense, or is it possible to associate select_relatedwith such a request ?:

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

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

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

class B(models.Model):
 c = models.ForeignKey(C)
+4
source share
1 answer

Try the following:

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

See documents

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 request:

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.
+4
source

Source: https://habr.com/ru/post/1610820/


All Articles