How to Update Objects in Django ORM: Syntax and Examples
To update objects in Django ORM, use the
update() method on a queryset to change multiple records at once or modify an individual object’s attributes and call save() to update it in the database. The update() method runs a direct SQL update, while save() triggers model methods and signals.Syntax
There are two main ways to update objects in Django ORM:
- Using
update()on a queryset: Updates all objects matched by the queryset in the database directly. - Using
save()on a model instance: Change attributes on a single object and callsave()to persist changes.
Example syntax:
Model.objects.filter(condition).update(field=value) obj = Model.objects.get(condition) obj.field = value obj.save()
python
Model.objects.filter(condition).update(field=value)
obj = Model.objects.get(condition)
obj.field = value
obj.save()Example
This example shows how to update a user's email using both update() and save() methods.
python
from django.db import models class User(models.Model): username = models.CharField(max_length=100) email = models.EmailField() # Update using update() method User.objects.filter(username='alice').update(email='alice_new@example.com') # Update using save() method user = User.objects.get(username='bob') user.email = 'bob_new@example.com' user.save()
Output
No output; database records for users 'alice' and 'bob' have updated emails.
Common Pitfalls
- Using
update()does not callsave()or trigger signals: So model methods likesave()overrides or signals won’t run. - For single objects, forgetting to call
save()after changing fields: Changes won’t be saved to the database. - Not filtering queryset before
update(): This can update all records unintentionally.
python
## Wrong: Forgetting to call save() user = User.objects.get(username='charlie') user.email = 'charlie_new@example.com' # Missing user.save() - changes not saved ## Right: Calling save() user.save()
Quick Reference
| Method | Use Case | Notes |
|---|---|---|
| update() | Update multiple objects at once | Direct DB update, no signals or save() called |
| save() | Update single object | Runs save(), triggers signals and validations |
| filter() | Select objects to update | Always filter to avoid updating all records |
| get() | Retrieve single object | Raises error if not found or multiple found |
Key Takeaways
Use queryset.update() to efficiently update multiple records without triggering save() or signals.
Modify fields on a model instance and call save() to update a single object and trigger model logic.
Always filter your queryset before calling update() to avoid unintended mass updates.
For single objects, never forget to call save() after changing fields to persist changes.
update() is faster for bulk updates but bypasses model methods and signals.