gpt4 book ai didi

python - Django select_related 不起作用

转载 作者:行者123 更新时间:2023-11-28 21:54:35 27 4
gpt4 key购买 nike

我的 django select_related 工作起来很奇怪

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'

输出:

books = Book.objects.select_related('publisher').all()
print books.query
SELECT "Book"."id", "Book"."name", "Book"."publisher_id", "Publisher"."id", "Publisher"."name" FROM "Book" INNER JOIN "Publisher" ON ( "Book"."publisher_id" = "Publisher"."id" )
print books.values()
[{'publisher_id': 1, u'id': 1, 'name': u'rest framework'}]

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

最佳答案

您稍微误解了selected_related 的工作原理。引用django docs on select_related :

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 QuerySet。

当您访问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 查找只是一个:

# Hits the database, but already includes Publisher data in the query
# SELECT "Book"."id", "Book"."name", "Book"."publisher_id", "Publisher"."id", "Publisher"."name" ...
b = Entry.objects.select_related('publisher').get(name='Twilight')

# Doesn't hit the database, because b.publisher has been prepopulated
# in the previous query.
p = b.publisher

(示例与 django docs 示例略有不同)

关于python - Django select_related 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24002297/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com