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")
相关推荐
隔壁大炮10 分钟前
MNE-Python 第6天学习笔记:分段(Epoching)与基线校正
python·eeg·mne·脑电数据处理
小a杰.13 分钟前
Ascend C算子开发实战 - 从零开始写算子
c语言·开发语言
雪度娃娃15 分钟前
Asio异步读写——连接的安全回收问题
开发语言·c++·安全·php
baivfhpwxf202320 分钟前
c# 中对像之间频繁的转换会慢吗?
开发语言·c#
SilentSamsara21 分钟前
concurrent.futures 实战:进程池与线程池的统一抽象
运维·开发语言·python·青少年编程
不吃土豆的马铃薯26 分钟前
Spdlog 进阶:日志基本控制、日志格式控制、异步记录器
linux·服务器·开发语言·前端·c++
水木流年追梦1 小时前
大模型入门-大模型的推理策略
开发语言·python·算法·正则表达式·prompt
l1t1 小时前
DeepSeek总结的将 Rust Delta Kernel 集成到 ClickHouse
数据库·clickhouse·rust
qq_283720051 小时前
万字深度:Chroma 向量数据库全解析 — 核心原理、实战操作、性能优化与工程最佳实践
数据库·性能优化
Cthy_hy1 小时前
Python 算法竞赛:数学核心知识点全总结
python·算法