gpt4 book ai didi

django - 预取相关之后选择相关

转载 作者:行者123 更新时间:2023-12-02 20:56:45 24 4
gpt4 key购买 nike

我的模型看起来像:

class Book(models.Model):
publisher = models.ForeignKey(Publisher) # This is not important

class Baz(models.Model):
a = models.CharField(max_length=100)

class Page(models.Model):
book = models.ForeignKey(Book)
baz = models.ForeignKey(Baz)

我正在尝试运行这样的查询:

[[x.baz.a for x in y.page_set.all()]
for y in Book.objects.all().prefetch_related('page_set', 'page_set__baz')]

我认为 ORM 应该能够执行两个查询:(Page JOIN Baz) 和 Book。最终连接应在 Python 中进行。相反,我看到 ORM 执行三个查询。我相信我必须知道如何使用 select_lated,但这也不起作用(在 prefetch_lated 之前移动 select_lated 也不起作用):

Book.objects.all().prefetch_related('page_set', 'page_set__baz').select_related('page_set__baz')

查询(上传是应用程序):

QUERY = u'SELECT "uploads_book"."id", "uploads_book"."publisher_id" FROM "uploads_book"' - PARAMS = (); args=()
QUERY = u'SELECT "uploads_page"."id", "uploads_page"."book_id", "uploads_page"."baz_id" FROM "uploads_page" WHERE "uploads_page"."book_id" IN (%s, %s)' - PARAMS = (1, 2); args=(1, 2)
QUERY = u'SELECT "uploads_baz"."id", "uploads_baz"."a" FROM "uploads_baz" WHERE "uploads_baz"."id" IN (%s)' - PARAMS = (1,); args=(1,)

这与此处的评论相关:prefetch_related for multiple Levels

最佳答案

您可以尝试使用Prefetch object

from django.db.models import Prefetch

page_qs = Page.objects.select_related('baz')
books = Book.objects.prefetch_related(Prefetch('page_set', queryset=page_qs))

关于django - 预取相关之后选择相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27121331/

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