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")
相关推荐
DanCheng-studio11 小时前
网安毕业设计简单的方向答疑
python·毕业设计·毕设
踢球的打工仔12 小时前
PHP面向对象(7)
android·开发语言·php
轻抚酸~12 小时前
KNN(K近邻算法)-python实现
python·算法·近邻算法
q***816413 小时前
MySQL:数据查询-limit
数据库·mysql
p***924813 小时前
DBeaver连接本地MySQL、创建数据库表的基础操作
数据库·mysql
独行soc13 小时前
2025年渗透测试面试题总结-264(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
汤姆yu14 小时前
基于python的外卖配送及数据分析系统
开发语言·python·外卖分析
Yue丶越14 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
JIngJaneIL14 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
如何原谅奋力过但无声14 小时前
TensorFlow 1.x常用函数总结(持续更新)
人工智能·python·tensorflow