Django select_相关的does n

2021-06-14 22:37:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我的django select_相关的工作非常奇怪

Models:
class Publisher(models.Model):
 name = models.CharField(max_length=100)
 class Meta:
      app_label = 'models'
      db_table = 'Publisher'
class Book(models.Model):
 name = models.CharField(max_length=100)
 publisher = models.OneToOneField(Publisher)
 class Meta:
      app_label = 'models'
     db_table = 'Book'

输出:

^{pr2}$

Django生成正确的查询,并在执行查询时检索数据。但值不包含Publisher

1条回答
网友
1楼 ·

您稍微误解了selected_related的工作原理。参考django docs on ^{}

select_related returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries.

正如您已经确定的那样,添加select_related会导致django选择相关对象的数据(Publisher.id&;Publisher.name在本例中)。但是,all()方法仍然只返回Book查询集。在

当您访问BookPublisher时,django将不需要再次查询数据库中的Publisher

# Hits the database.
# SELECT "Book"."id", "Book"."name", "Book"."publisher_id" ...
b = Book.objects.get(name='Twilight')

# Hits the database again to get the related Book object.
# SELECT "Publisher"."id", "Publisher"."name" ...
p = b.publisher

这是两个数据库查询,而select_related查找只有一个:

^{pr2}$

(示例是django docs示例的细微变化)

相关问题