I'm trying to make working postgresql database with sqlalchemy2 with async sessionmaker. Before i used concurent session which was without problem.
Now to my problem.
I've got this table
class GuildDB(database.base):
__tablename__ = "guild"
id: Mapped[str] = mapped_column(primary_key=True)
phrases: Mapped[set[GuildPhraseDB]] = relationship(back_populates="guild", cascade="all, delete", collection_class=set, lazy="selectin")
info_channel_id: Mapped[str] = mapped_column(nullable=True)
@hybrid_property
async def phrases_dict_prop(self) -> dict[str, str]:
return {phrase.key: phrase.value for phrase in self.phrases}
@classmethod
async def get_guild(cls, guild_id: str) -> GuildDB:
async with database.get_session() as session:
guild = await session.get(cls, guild_id)
if not guild:
guild = await cls.add_guild(guild_id)
return guild
@classmethod
async def add_guild(cls, guild_id: str) -> GuildDB:
async with database.get_session() as session:
guild = cls(id=guild_id)
session.add(guild)
await session.commit()
return guild
Whenever i try to access the phrases_dict_prop
guild = await GuildDB.get_guild(guild_id)
print(await guild.phrases_dict_prop)
i get
Parent instance <GuildDB at 0x783323209be0> is not bound to a Session; lazy load operation of attribute 'phrases' cannot proceed
My session maker
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from config.app_config import config
class Database:
def __init__(self):
self.base = declarative_base()
self.engine = create_async_engine(config.db_string, echo=False)
self.session = sessionmaker(self.engine, expire_on_commit=False, class_=AsyncSession)
def get_session(self) -> AsyncSession:
return self.session()
database = Database()
I had the impression that setting the relationship it to lazy="selectin" with expire_on_commit=False would make it possible