Make use of more SQLAlchemy Utils

This commit is contained in:
Daniil Fajnberg 2022-07-01 17:17:52 +02:00
parent b7e627a216
commit 8a8ea7ec09
3 changed files with 7 additions and 1 deletions

View File

@ -3,4 +3,5 @@ FastAPI
SQLAlchemy[asyncio]
Alembic
SQLAlchemy-Utils
Babel
python-slugify

View File

@ -28,6 +28,7 @@ install_requires =
SQLAlchemy[asyncio]
Alembic
SQLAlchemy-Utils
Babel
python-slugify
[options.extras_require]

View File

@ -3,6 +3,8 @@ from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.sql.functions import now as db_now
from sqlalchemy.sql.schema import Column
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy_utils.functions.orm import get_columns
from sqlalchemy_utils.listeners import force_auto_coercion
from compub.exceptions import NoDatabaseConfigured
from compub.settings import settings
@ -14,6 +16,8 @@ engine = create_async_engine(settings.db_uri, future=True)
LocalAsyncSession = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
ORMBase = declarative_base()
force_auto_coercion()
class AbstractBase(ORMBase):
__abstract__ = True
@ -25,7 +29,7 @@ class AbstractBase(ORMBase):
def __repr__(self) -> str:
# Exclude non-representative fields:
fields = (name for name in self.__mapper__.columns.keys() if name not in self.NON_REPR_FIELDS)
fields = (name for name in get_columns(self).keys() if name not in self.NON_REPR_FIELDS)
# Exclude NULL value fields:
attrs = ', '.join(f"{name}={repr(getattr(self, name))}" for name in fields if getattr(self, name) is not None)
return f"{self.__class__.__name__}({attrs})"