Updating existing records

Once a model instance has a primary key, any subsequent call to save() will result in an UPDATE rather than another INSERT. The model’s primary key will not change:

  1. >>> user.save() # save() returns the number of rows modified.
  2. 1
  3. >>> user.id
  4. 1
  5. >>> user.save()
  6. >>> user.id
  7. 1
  8. >>> huey.save()
  9. 1
  10. >>> huey.id
  11. 2

If you want to update multiple records, issue an UPDATE query. The following example will update all Tweet objects, marking them as published, if they were created before today. Model.update() accepts keyword arguments where the keys correspond to the model’s field names:

  1. >>> today = datetime.today()
  2. >>> query = Tweet.update(is_published=True).where(Tweet.creation_date < today)
  3. >>> query.execute() # Returns the number of rows that were updated.
  4. 4

For more information, see the documentation on Model.update() and Update.

Note

If you would like more information on performing atomic updates (such as incrementing the value of a column), check out the atomic update recipes.