← Back to Django, page 2

django-0024 · Medium mid

What are Django signals, how do you use post_save, and when should you avoid signals?

Signals let one part of the code react to events sent elsewhere, such as post_save after a model is saved. You connect a receiver with @receiver(post_save, sender=Model) and usually register it in AppConfig.ready(). Signals run synchronously in the same transaction, are skipped by bulk operations and update(), and hide control flow, so explicit service functions are often clearer.

Full answer

A signal is an event with subscribers. Built-in model signals include pre_save, post_save, pre_delete, post_delete and m2m_changed. There are also request signals (request_started, request_finished) and auth signals (user_logged_in, user_login_failed).

Connecting a receiver:

python
@receiver(post_save, sender=Student)
def create_report_card(sender, instance, created, **kwargs):
    if created:
        ReportCard.objects.create(student=instance)

Put receivers in signals.py and import it in AppConfig.ready() so they register once at startup.

Facts that matter in interviews:

  • Signals are synchronous. The receiver runs inside save(), in the same thread and database transaction. A slow receiver slows the request; an exception in it bubbles up to the caller.
  • QuerySet.update(), bulk_create() (no post_save per object), bulk_update() and raw SQL do not send pre_save/post_save.
  • created tells you whether this was an insert.
  • Use dispatch_uid to avoid connecting the same receiver twice.
  • If a receiver sends email or calls an API, wrap it in transaction.on_commit() so it only fires after the data is really committed.

When to avoid them: if the reacting code lives in your own app, calling a service function directly (enrol_student() that creates the student and the report card) is easier to read, test and debug. Signals shine when you need to react to models you do not own, such as a third-party app's User, or when a reusable app wants to let other apps hook in without importing them.

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()

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


class Student(models.Model):
    name = models.CharField(max_length=40)
    class Meta:
        app_label = "school"


class ReportCard(models.Model):
    student = models.OneToOneField(Student, on_delete=models.CASCADE)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)
    editor.create_model(ReportCard)

outbox = []


@receiver(post_save, sender=Student, dispatch_uid="student_report_card")
def create_report_card(sender, instance, created, **kwargs):
    if created:
        ReportCard.objects.create(student=instance)
        transaction.on_commit(lambda: outbox.append(f"welcome mail to {instance.name}"))


with transaction.atomic():
    s = Student.objects.create(name="Dev")
    print("inside transaction, outbox:", outbox)
print("after commit, outbox:", outbox)
print("report card exists:", ReportCard.objects.filter(student=s).exists())

s.name = "Dev Patel"
s.save()  # created=False, no second card
print("cards:", ReportCard.objects.count())

Student.objects.bulk_create([Student(name="Lina")])
print("cards after bulk_create:", ReportCard.objects.count())

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): inside transaction, outbox: [] after commit, outbox: ['welcome mail to Dev'] report card exists: True cards: 1 cards after bulk_create: 1

Key points

  • Signals are synchronous and share the caller's transaction
  • Register receivers in AppConfig.ready()
  • update(), bulk ops and raw SQL skip save signals
  • Use on_commit for side effects like emails
  • Prefer explicit service functions for your own models

Common mistakes

  • Expecting post_save to run after bulk_create() or update()
  • Sending emails directly in a receiver before the transaction commits
  • Using signals for logic inside your own app, making the flow hard to follow
  • Registering receivers in models.py imports that run twice, without dispatch_uid

Follow-ups

  • How would you test a signal receiver in isolation?
  • What happens if a post_save receiver raises an exception?
  • How is m2m_changed different from post_save?

Tips

  • State that signals are synchronous, many candidates think they are async
  • List the operations that skip signals
  • Give one case where signals are the right tool and one where they are not