Updating existing records

Once a model instance has a primary key, any subsequent call tosave() 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 followingexample will update all Tweet objects, marking them as published, if theywere created before today. Model.update() accepts keyword argumentswhere 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(),Update and Model.bulk_update().

Note

If you would like more information on performing atomic updates (such asincrementing the value of a column), check out the atomic updaterecipes.