【发布时间】:2022-12-18 01:41:08
【问题描述】:
我正在尝试获取一对多关系中匹配的行数。当我尝试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 need 0 here, as of now this parent has no children asyncio.run(main())
【问题讨论】:
标签: python sqlite sqlalchemy sqlmodel