链外键上的Django select_related

Fot*_* Sk 9 django django-queryset django-select-related

我在这里阅读了文档和所有相关问题,但我还没有正确理解select_related在链接/多个外键上的行为。

假设我们有以下模型:

class RecordLabel(models.Model):
   title = models.CharField(...)

class Band(models.Model):
   band_name = models.CharField(...)

class Artist(models.Model):
   record_label = models.ForeignKey(RecordLabel,...)
   belongs_to_band = models.ForeignKey(Band, ...)

class Producer(models.Model):
   customer = models.ForeignKey(Artist, ...)
Run Code Online (Sandbox Code Playgroud)

A.我们将如何在 a 中使用 select_related

Producer.objects.filter(...).select_related(?)
Run Code Online (Sandbox Code Playgroud)

查询以便预加载所有内容?会不会是这样:

Producer.objects.filter(...).select_related(
    'customer__record_label', 'customer__belongs_to_band')
Run Code Online (Sandbox Code Playgroud)

为什么?

B.如果班级有“流派”作为外键,

 class Genre(models.Model):
       genre_name = models.CharField(...)        

 class Band(models.Model):
       band_name = models.CharField(...)
       music_genre = models.ForeignKey(Genres, ...)
Run Code Online (Sandbox Code Playgroud)

然后为了预加载所有内容,我们将执行以下操作:

Producer.objects.filter(...).select_related(
    'customer__record_label__music_genre', 'customer__record_label__band_name',
    'customer__belongs_to_band__music_genre', 'customer__belongs_to_band__music_genre') 
Run Code Online (Sandbox Code Playgroud)

或类似的东西:

Producer.objects.filter(...).select_related(
    'customer__record_label__music_genre', 'customer__record_label__band_name',
    'customer__belongs_to_band', 'customer__belongs_to_band') 
Run Code Online (Sandbox Code Playgroud)

Ral*_*alf 8

关于问题B:

如果我正确理解您的问题,您只需指定一次字段,无需重复。

注意:我在这里再次显示您模型的最终版本,否则我会感到困惑。

class RecordLabel(models.Model):
    title = models.CharField(...)

class Genre(models.Model):
    genre_name = models.CharField(...)

class Band(models.Model):
    band_name = models.CharField(...)
    music_genre = models.ForeignKey(Genre, ...)

class Artist(models.Model):
    record_label = models.ForeignKey(RecordLabel, ...)
    belongs_to_band = models.ForeignKey(Band, ...)

class Producer(models.Model):
    customer = models.ForeignKey(Artist, ...)
Run Code Online (Sandbox Code Playgroud)

要选择所有相关模型(进行一个大连接 SQL 查询):

qs = Producer.objects.filter(...).select_related(
    'customer__record_label',
    'customer__belongs_to_band__music_genre')
Run Code Online (Sandbox Code Playgroud)

第一部分 ( customer) 预取相关艺术家和相关唱片公司 ( __record_label);第二部分不需要获取艺术家,因为它已经存在,但它会继续预取相关乐队 ( __belongs_to_band) 和相关流派 ( __music_genre)。现在您有一个访问所有 5 个表(模型)的 SQL 查询。

提示:您可以使用qs.query查看查询将生成的 SQL 语句的基本概念;这应该让您了解它所做的连接。

如果您在查询时遇到问题,那么您应该添加更多关于究竟发生了什么以及您期望什么的信息。