I have classes subclassing from sqlalchemy.orm.DeclarativeBase
class, I want to implement a class to be used as a (crud manager) : a class with crud methods that all my database models can use. here is a snippet of the how I'm implementing this:
class User(Base):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(50))
def __init__(self, **kw: Any):
self.manager = Manager(self, Maker)
super().__init__(**kw)
class Manager:
"""
Class representing crud manager
Attributes:
model: Base
manager: sqlalchemy.sessionmaker
"""
def __init__(self, model: Base, maker: sessionmaker) -> None:
self.model = model
self.maker = maker
def get(self, pk: int) -> Union[Base, None]:
"Query an instance of `self.model` by id"
with self.maker() as session:
stmt = select(self.model.__class__).where(id == pk)
res = session.execute(stmt).first()
return res
def create(self, data: List[Dict]) -> List[Base]:
...
sessionmaker
returns a database session.