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")
相关推荐
Via_Neo1 分钟前
JAVA中以2为底的对数表示方式
java·开发语言
书到用时方恨少!6 分钟前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
cch891810 分钟前
PHP五大后台框架横向对比
开发语言·php
孟章豪26 分钟前
《SQL拼接 vs 参数化,为什么公司禁止拼接SQL?(附真实案例)》
服务器·数据库·sql
荒川之神32 分钟前
ORACLE LEVEL函数练习
数据库·oracle
Warson_L36 分钟前
Python 常用内置标准库
python
·云扬·1 小时前
【MySQL】实战:用pt-table-sync修复主从数据一致性问题
数据库·mysql·ffmpeg
天真萌泪1 小时前
JS逆向自用
开发语言·javascript·ecmascript
Warson_L1 小时前
Python 函数的艺术 (Functions)
python
Warson_L1 小时前
Python 流程控制与逻辑
后端·python