Search code examples
pythonpython-3.xsqlalchemy

Way to update exitsting row from db sqlalchemy orm


Is there function updates data from db ex:

user = User()
user.name = 'Jonh'

session.add(user)
session.commit()

session.foo(user)

print(user.id) # now we have id of user

ps: i am looking for foo() function

i tried to use google and search in documentation but i didn't find solution


Solution

  • No, unfortunately, there's not any existing method for the aim you want to achieve. But you can achieve the same aim through updating the object "user" with its identity (ID):

    from sqlalchemy.orm import sessionmaker
    from sqlalchemy import create_engine
    
    engine = create_engine('sqlite:///users_database.db')
    Session = sessionmaker(bind=engine)
    session = Session()
    
    class User(Base):
        __tablename__ = 'users_table'
        id = Column(Integer, primary_key=True)
        name = Column(String)
    
    user = User(name='John')
    session.add(user)
    session.commit()
    
    session.refresh(user)
    
    print(user.id)
    

    You can use the built-in refresh() method in order to reload the object state from the database you're working on.