【发布时间】:2026-02-13 09:55:01
【问题描述】:
我想知道 SQLAlchemy 如何跟踪在 SQLAlchemy 之外进行的更改(例如手动更改)?
直到现在,我曾经把db.session.commit() 放在每个可以在 SQLAlchemy 之外更改的值之前。这是一个不好的做法吗?如果是,是否有更好的方法来确保我将获得最新价值?我实际上在下面创建了一个小脚本来检查这一点,显然,SQLAlchemy 可以检测外部更改,而无需每次都调用 db.session.commit()。
谢谢,
P.S:我真的很想了解 SQLAlchemy 背后的所有魔法是如何发生的。有没有人指向一些解释 SQLAlchemy 幕后工作的文档?
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Use SQLlite so this example can be run anywhere.
# On Mysql, the same behaviour is observed
basedir = os.path.abspath(os.path.dirname(__file__))
db_path = os.path.join(basedir, "app.db")
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + db_path
db = SQLAlchemy(app)
# A small class to use in the test
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
# Create all the tables and a fake data
db.create_all()
user = User(name="old name")
db.session.add(user)
db.session.commit()
@app.route('/')
def index():
"""The scenario: the first request returns "old name" as expected.
Then, I modify the name of User:1 to "new name" directly on the database.
On the next request, "new name" will be returned.
My question is: how SQLAlchemy knows that the value has been changed?
"""
# Before, I always use db.session.commit()
# to make sure that the latest value is fetched.
# Without db.session.commit(),
# SQLAlchemy still can track change made on User.name
# print "refresh db"
# db.session.commit()
u = User.query.filter_by(id=1).first()
return u.name
app.run(debug=True)
【问题讨论】:
标签: python orm flask sqlalchemy flask-sqlalchemy