0
0
DjangoHow-ToBeginner · 3 min read

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 call save() 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 call save() or trigger signals: So model methods like save() 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

MethodUse CaseNotes
update()Update multiple objects at onceDirect DB update, no signals or save() called
save()Update single objectRuns save(), triggers signals and validations
filter()Select objects to updateAlways filter to avoid updating all records
get()Retrieve single objectRaises 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.