SQLAlchemy supports "mixins," which are partial classes that define functionality when multi-inheritance is used to declare a table class. An example is the TablenameMixin class, which automatically creates a table name based on the class's name (i.e. a class named UserComment would be named usercomments).
importsqlalchemyassaimportsqlalchemy.ormassofromyour_database_module.baseimportBaseclassTableNameMixin:"""Mixin to automatically name tables based on class name. Generates a `__tablename__` for classes inheriting from this mixin. """@so.declared_attr.directivedef__tablename__(cls)->str:returncls.__name__.lower()+"s"classUserComment(Base,TabeNameMixin):## No need to declare a table name, the table will be named 'usercomments'# __table_name__ = "user_comments_tbl"...
fromdatetimeimportdatetimeimportsqlalchemyassaimportsqlalchemy.ormassoclassTimestampMixin:"""Add a created_at & updated_at column to records. Add to class declaration to automatically create these columns on records. Usage: py linenums=1 class Record(Base, TimestampMixin): __tablename__ = ... ... """created_at:so.Mapped[datetime]=so.mapped_column(sa.TIMESTAMP,server_default=sa.func.now())updated_at:so.Mapped[datetime]=so.mapped_column(sa.TIMESTAMP,server_default=sa.func.now(),onupdate=sa.func.now())
classTableNameMixin:"""Mixin to automatically name tables based on class name. Generates a `__tablename__` for classes inheriting from this mixin. """@so.declared_attr.directivedef__tablename__(cls)->str:# noqa: D105returncls.__name__.lower()+"s"