The Python Oracle

How to update SQLAlchemy row entry?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping

--

Chapters
00:00 Question
00:48 Accepted answer (Score 190)
00:58 Answer 2 (Score 513)
01:26 Answer 3 (Score 59)
03:30 Answer 4 (Score 7)
04:01 Thank you

--

Full question
https://stackoverflow.com/questions/9667...

Answer 3 links:
[SQLAlchemy: What's the difference between flush() and commit()?]: https://stackoverflow.com/questions/4201...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sqlalchemy #flasksqlalchemy

#avk47



ANSWER 1

Score 561


There are several ways to UPDATE using SQLAlchemy:

  1. user.no_of_logins += 1
    session.commit()
    
  2. session.query(User).\
        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()
    



ACCEPTED ANSWER

Score 206


user.no_of_logins += 1
session.commit()



ANSWER 3

Score 8


I wrote telegram bot, and have some problem with update rows. Use this example, if you 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()? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?




ANSWER 4

Score 6


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.