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)
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.