The Python Oracle

How to update SQLAlchemy row entry?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 How To Update Sqlalchemy Row Entry?
00:38 Accepted Answer Score 206
00:45 Answer 2 Score 6
01:09 Answer 3 Score 561
01:30 Answer 4 Score 8
01:55 Thank you

--

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

--

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.