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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With