python - SqlAlchemy 更新不适用于 Sqlite

标签 python sqlalchemy flask flask-sqlalchemy

我遵循了这个问题中的(两个)示例:SQLAlchemy: a better way for update with declarative?

而且我发现在 Ubuntu Linux 上使用带有 flask-sqlalchemy 的 sqlite 时不会发生模型更新。最简单的例子对我不起作用:

class Task:
    id= db.Column(db.Integer, primary_key=True)
    name= db.Column(db.String(32), unique=True)
    desc= db.Column(db.String(255), unique=False)
    state= db.Column(db.Boolean)

    # ...

@app.route("/task/<int:id>/update",methods=["POST"])
def toggle_state(id):
    db.session.query(Task).get(id).update({"state":True})
    log.info("state is now: " + str(Task.query.get(id).state))
    # prints "state is now: False"

第一次使用 flask/sqlalchemy,所以我想我遗漏了一些明显的东西。

最佳答案

所以我尝试了几种不同的方法。以下是不起作用的方法,以及最终起作用的方法:

没用:

# this will throw an exception, "AttributeError: 'Task' object has no attribute 'update'"
db.session.query(Task).get(id).update({"state":state})
db.session.commit()

# this was the example in the linked SO thread:
# does nothing
db.session.query(Task).filter_by(id=id).update({"state":state})

#this also does nothing
task = Task.query.filter_by(id=id)
task.state = state
db.session.commit()

#not this either
task = Task.query.get(id)
task.state = state
db.session.commit()

成功了:

#ok this works:
db.session.query(Task).filter_by(id=id).update({"state":state})
db.session.commit()

#and also this:
task = db.session.query(Task).get(id)
task.state = state
db.session.commit()

关于python - SqlAlchemy 更新不适用于 Sqlite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21803278/

相关文章:

python - 缺少必需的位置参数(日期时间)

python - OpenCV 概率霍夫线变换使用 C++ 和 Python 给出不同的结果?

在 github 操作中运行时不会发生 Python 自动版本控制

python - 将字典传递给 OrderedDict 有什么问题?

python - 用 uuid 替换整数 id 字段

python - MongoEngine 改变数据库

python - 如何调试未调用的 __del__()

python - sqlalchemy 和 SQLite 共享缓存

python - SQLAlchemy 按分钟分组

routes - 在 Flask 中阻止特定路由上的引荐来源网址