Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy update not working with Sqlite

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.

like image 733
Kevin Avatar asked Feb 15 '14 20:02

Kevin


1 Answers

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()
like image 108
Kevin Avatar answered Sep 28 '22 08:09

Kevin