我的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
答案 0 :(得分:3)
您对selected_related
的工作方式略有误解。参考django docs on select_related
:
select_related
会返回一个“跟随”外键关系的QuerySet, 在执行查询时选择其他相关对象数据。 这是一个性能提升,这会导致一个更复杂的问题 查询但意味着以后使用外键关系不需要 数据库查询。
正如您已经确定的那样,添加select_related
会导致django选择相关对象的数据(在这种情况下为Publisher.id
& Publisher.name
)。但是,all()
方法仍将仅返回Book
QuerySet。
有用的是当您访问Book
的{{1}}时,django不需要再次查询数据库Publisher
:
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
(例如,django docs示例略有变化)