from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import DeclarativeMeta
class BaseController:
"""
Base BaseController, implement base CRUD sqlalchemy operations
"""
model_cls = None
base_filter = ()
def get_by_id(
cls,
model_id: Union[int, str],
query_field: Union[List, tuple] = None,
to_dict: bool = False,
id_field: str = None,
) -> Model or None:
session.query(cls.model_cls).filter
class CustomDeclarativeMeta(DeclarativeMeta):
def __init__(self, *args, **kwargs):
super(CustomDeclarativeMeta, self).__init__(*args, **kwargs)
if hasattr(self, 'objects'):
self.objects.model_cls = self
self.objects.base_filter = (self.objects.model_cls.is_delete == 0,)
Base = declarative_base(metaclass=CustomDeclarativeMeta)
class BaseModel(Base):
"""基类表模板"""
__abstract__ = True
objects = BaseController()
is_delete = Column(Boolean, nullable=False, default=False, comment="是否已删除")
class User(BaseModel):
nickname = Column("nickname", String(255), index=True, comment="昵称")
User.objects.get_by_id(1)
1
XueXianqi 2023-09-05 17:31:42 +08:00
`get_by_id` 既然是个类方法,就需要加装饰器 `@classmethod`,而且出参的类型提示 `Model or None` 也不对,可能是 Model 或者 None 应该用 Optional[Model],况且这个方法里面也没有 return 任何内容,返回一定是 None ,逻辑有点问题...
|
2
wuwukai007 OP 就是为了不用类方法才用的元类,另外这个方法 pass ,只是提供了一个入口,自己实现
|