I am trying to get the number of rows matched in a one to many relationship. When I try parent.children_count
I get :
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)
I added expire_on_commit=False
but still get the same error. How can I fix this?
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'}
to my model, do I have to run alembic and create a migration script, the current table is configured without thesa_relationship_kwargs
? – Cotidal