为了账号安全,请及时绑定邮箱和手机立即绑定

sqlalchemy @hybrid_property v @propert

sqlalchemy @hybrid_property v @propert

白板的微信 2023-09-19 17:20:03
我有一个模型(我将其用作抽象基类),它具有一些常见的方法和属性。SQLAlchemy 允许使用 和 创建属性和方法,@hybrid_property而且@hybrid_method标准@property, @classmethod,@staticmethod装饰器也可以给我我想要的结果。与标准 python 装饰器相比,使用 SQLA 装饰器有什么优点和缺点?我什么时候应该使用或不应该使用 SQLA 装饰器?
查看完整描述

1 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

该混合提供了一个既可以在 Python 级别也可以在 SQL 表达式级别工作的表达式


让我们看一个例子:


class User(Base):

    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)

    firstname = Column(String(50))

    lastname = Column(String(50))


    @hybrid_property

    def fullname(self):

        return self.firstname + ' ' + self.lastname


    @property

    def long_name(self):

        return self.firstname + ' ' + self.lastname



session.add(User(firstname='Brendan', lastname='Simon'))

session.commit()

# error

# print(session.query(User).filter(User.long_name == 'Brendan Simon').first().id)

# works fine because @hybrid_property

print(session.query(User).filter(User.fullname == 'Brendan Simon').first().id)

您还可以SQL expression使用@fullname.expression进行自定义。


我什么时候应该使用或不应该使用 SQLA 装饰器?


我想当你需要的时候你就会知道。例如,您可以将其用于快速别名:


class MetaData(Base):

    __tablename__ = 'meta_data'

    system_field = Column(String(20))  # a lot of calculations and processing in different places

    # a lot of fields ...

有一天,几个部分system_field被(或将)重命名为new_field(不重要为什么,谁和何时 - 只是事实)。您可以执行以下操作作为快速解决方案:


@hybrid_property

def new_field(self):

    return self.system_field


@new_field.setter

def new_field(self, value: str):

    self.system_field = value


# data from somewhere...

# data = {'new_field': 'default', other fields...}

# will works fine + in other places will work as `system_field` with old sql queries

process_meta(MetaData(**{data}))

所以这确实是一个很好的功能,但是如果你正在考虑是否需要它,那么你肯定不需要它。


查看完整回答
反对 回复 2023-09-19
  • 1 回答
  • 0 关注
  • 187 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信