我尝试获取一对多关系中匹配的行数。当我尝试parent.children_count
时,得到:
sqlalchemy.exc.MissingGreenlet:未调用greenlet_spawn;无法在此处调用await_only()。是否在意外位置尝试IO?(此错误的背景信息位于:https://sqlalche.me/e/14/xd2s)
我添加了expire_on_commit=False
,但仍然得到相同的错误。我该如何修复此错误?
import asyncio
from uuid import UUID, uuid4
from sqlmodel import SQLModel, Relationship, Field
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
class Parent(SQLModel, table=True):
id: UUID = Field(default_factory=uuid4, primary_key=True)
children: list["Child"] = Relationship(back_populates="parent")
@property
def children_count(self):
return len(self.children)
class Child(SQLModel, table=True):
id: UUID = Field(default_factory=uuid4, primary_key=True)
parent_id: UUID = Field(default=None, foreign_key=Parent.id)
parent: "Parent" = Relationship(back_populates="children")
async def main():
engine = create_async_engine("sqlite+aiosqlite://")
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async with AsyncSession(engine) as session:
parent = Parent()
session.add(parent)
await session.commit()
await session.refresh(parent)
print(parent.children_count) # I expect 0 here, as of now this parent has no children
asyncio.run(main())
1条答案
按热度按时间yizd12fk1#
我认为这里的问题是默认情况下SQLAlchemy延迟加载关系,因此访问
parent.children_count
会隐式触发数据库查询,从而导致报告的错误。解决此问题的一种方法是在关系定义中指定“惰性”以外的加载策略。使用SQLModel时,如下所示:
这将导致SQLAlchemy发出额外的查询来获取关系,同时仍然处于“异步模式”。另一个选项是传递
{'lazy': 'joined'}
,这将导致SQLAlchemy在单个JOIN
查询中获取所有结果。如果不需要配置关系,则可以发出指定以下选项的查询: