Assume table has three columns: username, password and no_of_logins.
When user tries to login, it's checked for an entry with a query like
user=User.query.filter_by(username=form.username.data).first()
If password matches, he proceeds further. What I would like to do is count how many times the user logged in. Thus whenever he successfully logs in, I would like to increment the no_of_logins field and store it back to the user table. I'm not sure how to run update query with SqlAlchemy.
user.no_of_logins += 1
session.commit()
There are several ways to UPDATE using sqlalchemy
1) user.no_of_logins += 1
session.commit()
2) session.query().\
filter(User.username == form.username.data).\
update({"no_of_logins": (User.no_of_logins +1)})
session.commit()
3) conn = engine.connect()
stmt = User.update().\
values(no_of_logins=(User.no_of_logins + 1)).\
where(User.username == form.username.data)
conn.execute(stmt)
4) setattr(user, 'no_of_logins', user.no_of_logins+1)
session.commit()
With the help of user=User.query.filter_by(username=form.username.data).first() statement you will get the specified user in user variable.
Now you can change the value of the new object variable like user.no_of_logins += 1 and save the changes with the session's commit method.
I wrote telegram bot, and have some problem with update rows. Use this example, if u have Model
def update_state(chat_id, state):
try:
value = Users.query.filter(Users.chat_id == str(chat_id)).first()
value.state = str(state)
db.session.flush()
db.session.commit()
#db.session.close()
except:
print('Error in def update_state')
Why use db.session.flush()? Thet's why >>> SQLAlchemy: What's the difference between flush() and commit()?
来源:https://stackoverflow.com/questions/9667138/how-to-update-sqlalchemy-row-entry