我正在尝试获取一对多关系中匹配的行数。当我尝试使用
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())
sa_relationship_kwargs={'lazy': 'selectin'}
,我是否需要运行alembic并创建迁移脚本?当前表格没有配置sa_relationship_kwargs
。 - Jake