wuwukai007
V2EX  ›  Python

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

By wuwukai007 at 2023 年 9 月 1 日 · 1448 次点击
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)

2 条回复  •  2023-09-05 18:02:21 +08:00
XueXianqi
   1
XueXianqi  
   2023 年 9 月 5 日
`get_by_id` 既然是个类方法,就需要加装饰器 `@classmethod`,而且出参的类型提示 `Model or None` 也不对,可能是 Model 或者 None 应该用 Optional[Model],况且这个方法里面也没有 return 任何内容,返回一定是 None ,逻辑有点问题...
wuwukai007
   2
wuwukai007  
OP
   2023 年 9 月 5 日
就是为了不用类方法才用的元类,另外这个方法 pass ,只是提供了一个入口,自己实现
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 24ms · 3.9.8.5