Bebe
Bebe

Reputation: 77

How to update a table using SqlAlchemy with python

Hi I am new to SQLAlchemy using python. I want to update a table called Cars and wanted some feedbacks if maybe there is another way of updating a table. I am not sure if execute() is good way of updating since it calls for a query. I have searched everywhere, but just trying a simple query and update.

Here is a graph I am following: enter image description here

Here is my code:

from cars.models import Cars
from cars.models import CarType
from sqlalchemy.orm import session
from sqlalchemy.sql.expression import update
from sqlalchemy.sql.sqltypes import String, Text

# To update cars
def update_cars_models(session):
  db = session

  try:
    state = db.query(Cars).filter(Cars.state == "PRE_PROCESS")

    for row in state.all():
      if row.state == "PRE_PROCESS":

        # To add CarType object data
        car_update = CarType(1, "Subaru", "WHITE", "PRE_PROCESS")
        db.add(car_update)
        db.commit()

        # To update Cars object
        row.state = Cars.State.PROCESS #not sure if this how you use update
        db.commit()

  except SQLAlchemyError as error:
    print(f"Error querying: {error}")

  finally:
    db.close()

if __name__ == "__main__":

    # To update cars
    update_cars_models(session)

Upvotes: 0

Views: 4133

Answers (1)

Hashir Irfan
Hashir Irfan

Reputation: 334

You do not have to query all the rows and then edit each row in a loop. Your code depicts that you want to update those rows whose state is "PRE_PROCESS"

car_update = { state = "PROCESS" }
rows_updated = (db.session.query
        .filter(Car.state == "PRE_PROCESS")
        .update(car_update)
    )

If you want to update a row for a specific ID, you can write "Car.id == 1" in filter

Upvotes: 1

Related Questions