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")
相关推荐
leihefeng10 分钟前
PX06-对比两个 Excel 文件的差异:从逐单元格到生产级实现
python·excel
小小龙学IT13 分钟前
Go 泛型(Generics)深度解析:从类型参数到生产实践
开发语言·数据库·golang
这个DBA有点耶17 分钟前
分区表深入:分区裁剪失效的6种场景、分区锁机制与维护实战
数据库·mysql·dba
hold?fish:palm22 分钟前
45 二叉树的右视图
开发语言·c++·算法
MI_farmer24 分钟前
Anaconda 安装在 D 盘但虚拟环境跑到 C 盘,以及 Conda PermissionError: WinError 5 的解决方法
c语言·开发语言·conda
Ticnix28 分钟前
MCP 上个月把自己推翻重写了:Session 没了、Sampling 废了——你学的教程还停在 2025
python·agent·全栈
蓝速科技30 分钟前
政务自助终端信创选型与无人值守落地方案
android·大数据·数据库·人工智能·科技·技术分享·政务
“AI国潮设计-小江”32 分钟前
[AIGC实战] 基于Stable Diffusion的潮汕非遗IP自动化生成工作流(附Python批量处理脚本)
开发语言·人工智能·python·prompt·aigc
LOVE️YOU37 分钟前
Python 中的 range 是类还是函数?range 对象该怎么理解?
python
粤鼎恒业1 小时前
惠州工厂电子料回收厂家推荐:从交接单反推筛选标准
大数据·数据库·算法·硬件架构·硬件工程·pcb工艺·材料工程