Updating Model Instances
Updating a Single Object
Fetch the object with .get(), change one or more attributes like normal Python attributes, then call .save() to write the change back.
Example: Updating a Single Object
Fetch the object with .get(), change one or more attributes like normal Python attributes, then call .save() to write the change back.
book = Book.objects.get(id=1)
book.pages = 300
book.save()
⚠️ Run this command in your terminal.
Updating Many Rows at Once
Calling .update() directly on a QuerySet changes every matching row in one database operation, without loading them into Python first.
Note: This is much faster than looping and calling .save() on each object individually.
Example: Updating Many Rows at Once
Calling .update() directly on a QuerySet changes every matching row in one database operation, without loading them into Python first.
Book.objects.filter(genre='Action').update(is_featured=True)
⚠️ Run this command in your terminal.
save() vs update()
save() works on a single already-fetched instance and runs any custom save logic or signals. update() works directly on a QuerySet and skips per-instance logic for speed.
Warning: update() does not call each object's .save() method, so post_save signals won't fire for it.
Example: save() vs update()
save() works on a single already-fetched instance and runs any custom save logic or signals. update() works directly on a QuerySet and skips per-instance logic for speed.
book = Book.objects.get(id=2)
book.title = 'New Title'
book.save()
Book.objects.filter(id=3).update(title='Bulk Title')
⚠️ Run this command in your terminal.
- Changing an attribute on a fetched instance but forgetting to call .save(), so the change never reaches the database.
- Using .filter(...).update(...) but expecting model .save() signals like post_save to fire — they don't, since update() bypasses .save().
- Fetching an object just to update one field, without realizing update_fields could make the save more precise and efficient.
- To update one object, fetch it, change its attributes, then call .save().
- QuerySet.update(...) can update many matching rows at once directly in the database.
- .save() re-writes the whole row; .update() changes only the specified fields in bulk.
- Bulk updates with .update() are faster but skip each object's .save() method and signals.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: