首页 > 解决方案 > 异步 SQLalchemy:访问急切加载的空关系会触发新的延迟加载,引发错误

问题描述

我正在使用 sqlalchemy + asyncpg 和“选择”急切加载。

我有与 Friends 具有一对多关系的 Person 项目。

我在我的数据库中插入了一个 Person,没有相关的 Friend 条目。如果在同一个会话中我尝试从数据库中获取那个人,我可以很好地访问他们的静态(非关系)列,但不能访问friends关系。

我认为尝试访问person.friends会触发延迟加载,尽管它之前是作为selectin加载强制执行的。为什么是这样?我怎样才能避免它?

# Create the ORM model
class Person(Base):
    __tablename__ = 'items'
    id_ = Column(POSTGRES_UUID(as_uuid=True), primary_key=True)
    name = Column(String(32))
    friends = relationship('Friend', lazy='selectin')

# Create an instance
person_id = uuid4()
person = Person(id_=person_id, name='Alice') # Note that this Person's friends are not set

# Add to database
async with AsyncSession(engine, expire_on_commit=False) as session:
    try:
        session.begin()
        session.add(person)
        await session.commit()
    except:
        await session.rollback()
        raise
    # Get the added person from the database
    created_person = await session.get(person, person_id)
    print(created_person.id_) # Works fine
    print(created_person.friends) # Raises error

错误:

sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here.
Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)

标签: asynchronoussqlalchemypython-asyncioasyncpg

解决方案


解决方案是使用以下populate_existing参数get

populate_existing – 使方法无条件地发出 SQL 查询并用新加载的数据刷新对象,而不管对象是否已经存在。

代替

created_person = await session.get(person, person_id)

created_person = await session.get(person, person_id, populate_existing=True)

session.get 文档

另见:https ://github.com/sqlalchemy/sqlalchemy/issues/7176


推荐阅读