我正在使用 sqlalchemy asyncpg 和“選擇”急切加載。
我有與朋友有一對多關系的個人專案。
我將一個 Person 插入到我的資料庫中,沒有相關的 Friend 條目。如果在同一個會話中我嘗試從資料庫中獲取那個 Person,我可以很好地訪問他們的靜態(非關系)列,但無法訪問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)
uj5u.com熱心網友回復:
解決方案是在 中使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321726.html
標籤:异步 sqlalchemy 蟒蛇异步 异步程序
