Learn the subtle differences between Save and Update in Django

Learn the subtle differences between Save and Update in Django
Learn the subtle differences between Save and Update in Django

Unravel the nuanced distinctions between Django's Save and Update functions. A deep dive into these two operations can illuminate their unique roles in data manipulation, enhancing your proficiency in Django and elevating your web development skills.

Save

The.save() method is used to write a model instance to the database.

  • For an existing record, Django will run a SQL UPDATE statement on the database, and for a new record, it will run an INSERT. Before Django 3.0, it would also do a SELECT before the INSERT, to make sure that the primary key doesn’t exist (if one was given).
  • If you have only a few fields to save, use the update_fields parameter.

When to use Update

You are updating fields of one or many records.

Use update instead

The SQL that is run against the database will be more efficient.

  • If you need to update field values, without any other model logic needing to be run, and you know what the changes will be without fetching the record(s) first, use update.
  • However, if you’ve already loaded the record from the database and you possibly need the change to be dynamic based on existing data or there’s attached model logic that needs to run, use save.

When to use Save

When you are creating a new record

Update

The.update() method is available on each queryset object of the ORM. Using it will typically look like this: Book.objects.filter(price__lt=10).update(price=10) This would update the price of all books that are below a certain price. Note that this does not increment the price like the first save example.

Source