python - Python mongoengine select_related(n) 没有达到我的预期
问题描述
我有一个存储在 mongo 中的对象,它有一个引用字段列表。在 restplus 应用程序中,我需要解析这个对象列表并将它们映射到 JSON 文档中以返回给客户端。
# Classes I have saved in Mongo
class ThingWithList(Document):
list_of_objects = ListField(ReferenceField(InfoHolder))
class InfoHolder(Document):
thing_id = StringField()
thing_i_care_about = ReferenceField(Info)
class Info(Document):
name = StringField()
foo = StringField()
bar = StringField()
我发现遍历列表非常慢。我猜是因为每次我取消引用列表中对象的子项时,我都必须进行另一个数据库查询。
简单(但垃圾)的方法:
info_to_return = []
thing = ThingWithList.get_from_id('thingsId')
for o in list_of_objects:
info = {
'id': o.id,
'name': o.thing_i_care_about.name,
'foo': o.thing_i_care_about.foo,
'bar': o.thing_i_care_about.bar
}
info_to_return.append(info)
return(info_to_return)
我想我可以通过使用 select_related 来解决这个问题,听起来它应该为我解引用 N 级深,这样我只做一个大的 mongo 调用,而不是每次迭代几次。当我添加
thing.select_related(3)
它似乎没有效果。我是不是误解了这个功能的用途。我还能如何加快查询速度?
解决方案
推荐阅读
- node.js - 我应该为graphql中的所有关系定义一对多关联并续集吗?
- amazon-web-services - AWS Athena - 解释查询计划
- python - Python:函数总是从循环中返回零
- php - 使用 XAMPP 或 Wamp 创建本地 WordPress 站点 ..但出现此错误..建立数据库连接时出错
- pytorch - 声明 PyTorch 张量时有关尺寸的 ValuerError
- json - 如何从json文件制作数据框表
- php - SSL 证书配置错误
- r - 如何按时间对 R 中的 XTS 对象进行分组?
- docker - Docker 占用所有空间 100%
- python - 如何将 2 因素身份验证与 Google Oauth Login 集成?