← Back to Django, page 4

django-0074 · Medium mid

What is the difference between save(), queryset.update() and bulk_update() in Django, in terms of queries, signals, auto_now fields and custom save logic?

save() loads nothing extra, runs the model's save() method and sends pre_save and post_save signals, and updates auto_now fields. queryset.update() issues a single UPDATE for all matching rows and skips save(), signals and auto_now. bulk_update(objs, fields) updates many objects in batches of CASE-based statements, also skipping save() and signals. Choose by whether you need side effects or speed.

Full answer
save()queryset.update()bulk_update()
SQLone UPDATE per objectone UPDATE for the whole queryseta few UPDATEs with CASE, batched
Custom save()runsskippedskipped
pre_save/post_save signalssentnot sentnot sent
auto_now fieldsrefreshednot touchednot touched
Needs objects in memoryyesnoyes
ReturnsNonerows matchedrows matched

When to use each:

  • save(): single objects and when your model has logic or listeners (audit log, cache invalidation). Pass update_fields=[...] to limit columns and avoid overwriting concurrent changes to other fields.
  • update(): the same change for many rows, ideally with F(): Fee.objects.filter(due__lt=today).update(amount=F("amount") + 50). It is atomic at the row level and the fastest. If you need auto_now, add updated=timezone.now() to the call.
  • bulk_update(): different values per object (for example after recalculating ranks in Python). Provide fields and a batch_size to keep statements within the database's parameter limit.

Consequences: code that relies on signals or save() overrides silently stops working when someone switches to update() for performance. Document this near the model, or put required side effects in a model manager or service function that is called deliberately. Also remember update() cannot be used on sliced querysets and cannot reference fields across joins directly.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import datetime

from django.db import models, connection
from django.db.models import F
from django.db.models.signals import post_save
from django.dispatch import receiver


class Fee(models.Model):
    roll_no = models.CharField(max_length=10)
    amount = models.IntegerField()
    updated = models.DateTimeField(auto_now=True)
    saves = models.IntegerField(default=0)

    class Meta:
        app_label = "school"

    def save(self, *args, **kwargs):
        self.saves += 1                                   # custom save() logic
        super().save(*args, **kwargs)


signals_seen = []


@receiver(post_save, sender=Fee)
def record(sender, instance, **kwargs):
    signals_seen.append(instance.roll_no)


with connection.schema_editor() as editor:
    editor.create_model(Fee)

Fee.objects.create(roll_no="A1", amount=100)
Fee.objects.create(roll_no="A2", amount=100)
signals_seen.clear()
Fee.objects.update(updated=datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc))     # freeze auto_now for the demo
old = Fee.objects.get(roll_no="A1").updated

print("update():", Fee.objects.update(amount=F("amount") + 50), "rows")
f = Fee.objects.get(roll_no="A1")
print("signals:", signals_seen, "| saves counter:", f.saves, "| auto_now changed:", f.updated != old)

f.amount = 999
f.save()
f = Fee.objects.get(roll_no="A1")
print("save():  signals:", signals_seen, "| saves counter:", f.saves, "| auto_now changed:", f.updated != old)

fees = list(Fee.objects.order_by("roll_no"))
for i, fee in enumerate(fees):
    fee.amount = 10 * (i + 1)
print("bulk_update():", Fee.objects.bulk_update(fees, ["amount"]), "rows | signals:", signals_seen)
print(list(Fee.objects.order_by("roll_no").values_list("amount", flat=True)))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): update(): 2 rows signals: [] | saves counter: 1 | auto_now changed: False save(): signals: ['A1'] | saves counter: 2 | auto_now changed: True bulk_update(): 2 rows | signals: ['A1'] [10, 20]

Key points

  • save() runs custom logic, signals and auto_now
  • update() is one SQL statement and skips all of those
  • bulk_update() sets different values per object in batches
  • Use F() with update() for race-safe changes
  • Side effects need an explicit place when update() is used

Common mistakes

  • Switching save() to update() for speed and losing signals or custom logic
  • Expecting auto_now to change with update() or bulk_update()
  • Forgetting update_fields and overwriting concurrent changes
  • Using bulk_update without batch_size on very large lists

Follow-ups

  • How would you keep an audit log when using bulk operations?
  • What does save(update_fields=[...]) emit as SQL?
  • Why does update() not work on a sliced queryset?

Tips

  • Fill a comparison from memory
  • Name the side effects that are skipped
  • Mention F() with update()