Updating an object

When you assign new values to object attributes, you don’t need to save each updated object manually. Changes will be saved in the database automatically on leaving the db_session() scope.

For example, in order to increase the number of products by 10 with a primary key of 123, you can use the following code:

  1. Product[123].quantity += 10

For changing several attributes of the same object, you can do so separately:

  1. order = Order[123]
  2. order.state = "Shipped"
  3. order.date_shipped = datetime.now()

or in a single line, using the set() method of an entity instance:

  1. order = Order[123]
  2. order.set(state="Shipped", date_shipped=datetime.now())

The set() method can be convenient when you need to update several object attributes at once from a dictionary:

  1. order.set(**dict_with_new_values)

If you need to save the updates to the database before the current database session is finished, you can use the flush() or commit() functions.

Pony always saves the changes accumulated in the db_session() cache automatically before executing the following methods: select(), get(), exists(), execute() and commit().

In future, Pony is going to support bulk update. It will allow updating multiple objects on the disk without loading them to the cache:

  1. update(p.set(price=price * 1.1) for p in Product
  2. if p.category.name == "T-Shirt")