0
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to the Code Review Community. We are quite different from stack overflow in some ways. Giving us snippets of code will be less effective than providing the source files. I suggest you read A guide to Code Review for Stack Overflow users. \$\endgroup\$
    – pacmaninbw
    Mar 9 at 13:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.