在 sqlalchemy 中实现 django User.objects.get_by_id 风格

249 天前
 wuwukai007
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)

625 次点击
所在节点    Python
2 条回复
XueXianqi
245 天前
`get_by_id` 既然是个类方法,就需要加装饰器 `@classmethod`,而且出参的类型提示 `Model or None` 也不对,可能是 Model 或者 None 应该用 Optional[Model],况且这个方法里面也没有 return 任何内容,返回一定是 None ,逻辑有点问题...
wuwukai007
245 天前
就是为了不用类方法才用的元类,另外这个方法 pass ,只是提供了一个入口,自己实现

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/970173

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX