推荐学习书目
› 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 · Sep 1, 2023 · 1486 views
    This topic created in 1135 days ago, the information mentioned may be changed or developed.
    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 replies  •  2023-09-05 18:02:21 +08:00
    XueXianqi
        1
    XueXianqi  
       Sep 5, 2023
    `get_by_id` 既然是个类方法,就需要加装饰器 `@classmethod`,而且出参的类型提示 `Model or None` 也不对,可能是 Model 或者 None 应该用 Optional[Model],况且这个方法里面也没有 return 任何内容,返回一定是 None ,逻辑有点问题...
    wuwukai007
        2
    wuwukai007  
    OP
       Sep 5, 2023
    就是为了不用类方法才用的元类,另外这个方法 pass ,只是提供了一个入口,自己实现
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   944 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 57ms · UTC 21:57 · PVG 05:57 · LAX 14:57 · JFK 17:57
    ♥ Do have faith in what you're doing.