V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
wuwukai007
V2EX  ›  Python

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

  •  
  •   wuwukai007 · 239 天前 · 618 次点击
    这是一个创建于 239 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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  
       235 天前
    `get_by_id` 既然是个类方法,就需要加装饰器 `@classmethod`,而且出参的类型提示 `Model or None` 也不对,可能是 Model 或者 None 应该用 Optional[Model],况且这个方法里面也没有 return 任何内容,返回一定是 None ,逻辑有点问题...
    wuwukai007
        2
    wuwukai007  
    OP
       235 天前
    就是为了不用类方法才用的元类,另外这个方法 pass ,只是提供了一个入口,自己实现
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2929 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 14:27 · PVG 22:27 · LAX 07:27 · JFK 10:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.