我被多个模型的连接加载问题困扰了。我有一个 FastAPI 项目,并且正在使用 Jinja 来提供一些 HTML 页面。在该页面中,我需要访问从其他表连接的内容(在 Jinja 模板中,似乎在执行访问时不起作用?我一直收到 greenlet 错误)。因为我肯定会获取上述数据,所以我对映射到其他模型的属性进行了连接加载:
statement = statement.options(
joinedload(Item.purchases),
joinedload(Item.purchases.receipt),
joinedload(Item.purchases.receipt.store),
)
但是,我收到此错误:
joinedload(Item.purchases.receipt),
^^^^^^^^^^^^^^^^^^^^^^
File "/app/.venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py", line 474, in __getattr__
raise AttributeError(
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Item.purchases has an attribute 'receipt'
此外,考虑到我要连接 4 个表,我觉得我应该尽量减少在连接过程中选择的列数,但我不知道该如何做到这一点。
要
joinedload
跨多个关系,您可以堆叠.joinedload()
调用:我假设
Purchase
和Receipt
是这些表的模型类。您可以在文档中阅读更多内容。