【问题标题】:SqlAlchemy update not working with SqliteSqlAlchemy 更新不适用于 Sqlite
【发布时间】:2014-03-15 05:25:26
【问题描述】:

我遵循了这个问题中的(两个)示例: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,所以我认为我遗漏了一些明显的东西。

【问题讨论】:

    标签: python sqlalchemy flask flask-sqlalchemy


    【解决方案1】:

    所以我尝试了几种不同的方法。以下是无效的,以及最终有效的:

    没用:

    # 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()
    

    【讨论】:

    • 声明式风格:session.query(Task).filter_by(id=id).update({"state":state})
    猜你喜欢
    • 2013-07-13
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2012-04-12
    • 2014-04-09
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多