这是我的实体:
class Article(db.Entity):
id = PrimaryKey(int, auto=True)
creation_time = Required(datetime)
last_modification_time = Optional(datetime, default=datetime.now)
title = Required(str)
contents = Required(str)
authors = Set('Author')
class Author(db.Entity):
id = PrimaryKey(int, auto=True)
first_name = Required(str)
last_name = Required(str)
articles = Set(Article)
这是我用来获取一些数据的代码:
return left_join((article, author) for article in entities.Article
for author in article.authors).prefetch(entities.Author)[:]
无论我是否使用预取方法,生成的 sql 看起来总是一样的:
SELECT DISTINCT "article"."id", "t-1"."author"
FROM "article" "article"
LEFT JOIN "article_author" "t-1"
ON "article"."id" = "t-1"."article"
然后当我迭代结果时,小马正在发出另一个查询(查询):
SELECT "id", "creation_time", "last_modification_time", "title", "contents"
FROM "article"
WHERE "id" = %(p1)s
SELECT "id", "first_name", "last_name"
FROM "author"
WHERE "id" IN (%(p1)s, %(p2)s)
我想要的行为是如果 orm 只发出一个查询来加载所有需要的数据。那么我该如何实现呢?