sqlalchemy 中的简单更新 [英] simple update in sqlalchemy

查看:31
本文介绍了sqlalchemy 中的简单更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户表是:

  • id (INT)

  • id (INT)

姓名 (STR)

last_login (DATETIME)

last_login (DATETIME)

处理网页请求,我手头有一个用户 ID,我只想将 last_login 字段更新为现在".

Serving a web page request i have a user id in hand and I only wish to update the last_login field to 'now'.

在我看来,有两种方法:

It seems to me that there are 2 ways:

  1. 使用 db_engine 发出直接 SQL(丢失映射器)

  1. issue a direct SQL using db_engine (losing the mapper)

OR 先查询用户再更新对象

OR query the user first and then update the object

两者都运行良好,但代码看起来很恶心.

Both work fine but look quite disgusting in code.

有没有人知道一种使用 sqlalchemy 进行无查询更新的更优雅的方法?有没有其他 ORM 做对了?

谢谢

推荐答案

假设您有一个映射器 UserTable:

Assuming you have a mapper UserTable in place:

DBSession.query(UserTable).filter_by(id = user_id).\
    update({"last_login":datetime.datetime.now()}, synchronize_session=False)

中的附加参数文档.

这篇关于sqlalchemy 中的简单更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆