sqlalchemy——@listens_for

  • 问:sqlalchemy如何实现:表中指定数据更新时,其time字段自动更新?
  • 答:使用listens_for 装饰器来注册事件监听器,确保在项目数据更新时触发相应的处理逻辑。

示例代码如下:

python 复制代码
# coding: utf-8
import datetime

from sqlalchemy.event import listens_for
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, String

Base = declarative_base()
'''
    项目表
'''

class ProjectTable(Base):
    __tablename__ = 'project'
    # 项目id
    id = Column(String(32), primary_key=True)
    # 项目名称
    name = Column(String(255))
    # 项目说明
    explain = Column(String(255))
    # 项目类型
    type = Column(String(20))
    # 更新时间
    time = Column(String(20), default=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    def __repr__(self):
        table = "project(id={}, name={}, explain={},time={},type={})"
        return table.format(self.id, self.name, self.explain, self.time, self.type)

    # 将查询结果转换为Json
    def to_json(self):
        _dict = self.__dict__
        if "_sa_instance_state" in _dict:
            del _dict["_sa_instance_state"]
        return _dict
# 添加监听,当数据更新时,自动更新time字段
@listens_for(ProjectTable, 'before_update')
def before_update_listener(mapper, connection, target):
    target.time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
相关推荐
用户2519162427112 小时前
Python之语言特点
python
RestCloud2 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
刘立军3 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
RestCloud3 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence5 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
数据智能老司机6 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机7 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i8 小时前
django中的FBV 和 CBV
python·django
c8i8 小时前
python中的闭包和装饰器
python
DemonAvenger12 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化