Updating Objects
In this chapter, we will see how to modify or update the table with desired values. To modify data of a certain attribute of any object, we have to assign new value to it and commit the changes to make the change persistent. Let us fetch an object from the table whose primary key identifier, in our Customers table with ID=2. We can use get() method of session as follows:
- x = session.query(Customers).get(2)
- print ("Name: ", x.name, "Address:", x.address, "Email:", x.email)
Now we need to update the Address field by assigning new value as given below:
- >>> x.address = 'Banjara Hills Secunderabad'
- >>> session.commit()
- 2019-04-18 14:56:28,346 INFO sqlalchemy.engine.base.Engine UPDATE customers SET address=%(address)s WHERE customers.id = %(customers_id)s
- 2019-04-18 14:56:28,346 INFO sqlalchemy.engine.base.Engine {'address': 'Banjara Hills Secunderabad', 'customers_id': 2}
- 2019-04-18 14:56:28,349 INFO sqlalchemy.engine.base.Engine COMMIT
- >>> x = session.query(Customers).filter(Customers.id == 2).first()
- 2019-04-18 14:59:19,520 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
- 2019-04-18 14:59:19,521 INFO sqlalchemy.engine.base.Engine SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email
- FROM customers
- WHERE customers.id = %(id_1)s
- LIMIT %(param_1)s
- 2019-04-18 14:59:19,521 INFO sqlalchemy.engine.base.Engine {'id_1': 2, 'param_1': 1}
- >>> print ("Name: ", x.name, "Address:", x.address, "Email:", x.email)
Now change name attribute and display the contents using the below code:
Even though the change is displayed, it is not committed. You can retain the earlier persistent position by using rollback() method with the code below:
For bulk updates, we shall use update() method of the Query object. Let us try and give a prefix, ‘Mr.’ to name in each row (Except ID = 2). The corresponding update() statement is as follows:
The update() method requires two parameters as follows:
Three out of 4 rows in the table will have name prefixed with ‘Mr.’ However, the changes are not committed and hence will not be reflected in the table view. It will be refreshed only when we commit the session.
沒有留言:
張貼留言