且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SqlAlchemy更新不与Sqlite一起使用

更新时间:2023-09-19 10:53:34

所以我尝试了几个不同的东西。这是什么不工作,什么最终没有工作:

没有工作:

pre > #这将抛出一个异常,AttributeError:任务'对象没有任何属性'更新'
db.session.query(Task).get(id).update({状态:状态})
db.session.commit()

#这是链接的SO线程中的示例:
#不做任何事
db.session .query(Task).filter_by(id = id).update({state:state})

#this也没有做任何事
task = Task.query.filter_by(id = id)
task.state = state
db.session.commit()

#不是
task = Task.query.get(id)
task.state = state
db.session.commit()



  #ok这样做:
db.session.query(Task).filter_by(id = id).update ({state:state})
db.session.commit()

#也是这样的:
task = db.session.query(Task).get id)
task.state =状态
db.session.commit()


I followed the (two) examples in this question: SQLAlchemy: a better way for update with declarative?

And I'm finding that a model update does not happen when using sqlite with flask-sqlalchemy on Ubuntu Linux. The very simplest example doesn't work for me:

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"

First time using flask/sqlalchemy, so I assume I'm missing something obvious.

So I tried several different things. Here's what didn't work, and what finally did work:

Didn't work:

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

Did work:

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