user8415999
user8415999

Reputation:

SQLalchemy Core, retrive id/s of the updated row/s

I am trying to learn how to use the SQlalchemy core properly and currently, I have this query.

        up = Airport.__table__.update().where(Airport.__table__.c.iata_code == iata_code).values(city=city)

I am using it to update values in a table that has this structure:

class Airport(Base):
    __tablename__ = 'airports'

    id = Column(Integer, primary_key=True)
    iata_code = Column(String(64), index=True, nullable=False)
    city = Column(String(256), nullable=False)

The problem is that after the execution of the update procedure I need the ids of the updated rows. Is it possible to update the values and obtain the ids in only one query? I would like to avoid to have to perform 2 queries for this operation.

The DBMS I am using is mysql.

Upvotes: 2

Views: 953

Answers (1)

Sunny Patel
Sunny Patel

Reputation: 8077

Disclaimer: This is for SQLAlchemy ORM, not Core

Get the object, and update it. SQLAlchemy will update the instance's ID in the same DB round trip.

airport = Airport.filter_by(Airport.__table__.c.iata_code == iata_code).first()
airport.city = city
db.session.commit()
print(airport.id)

Upvotes: 1

Related Questions