Introducing Django Signals and the Observer Pattern
1️⃣ Core Concepts Recap (Very Brief)
• pre_save, post_save, pre_delete, post_delete
• connect(), disconnect(), @receiver
• Synchronous vs asynchronous signals (Django 4.1+)
2️⃣ Advanced Signal Usage
• Listening to custom signals
• Sending your own signal with Signal(providing_args=...)
• Signal chaining (calling multiple receivers)
• Sending extra context/data via kwargs
3️⃣ Real-World Use Cases
• Auto-creating related models (e.g. Profile on User creation)
• Logging actions or triggering side effects (e.g. sending notifications)
• Syncing data across models or apps
• Clean-up tasks on deletion
4️⃣ Best Practices
• ✅ Keep signal receivers small — avoid heavy logic
• ✅ Avoid DB writes in signals when possible
• ✅ Use signals for decoupled side effects, not primary logic
• ✅ Always document what your signals are doing
• ✅ Use dispatch_uid to avoid duplicate execution
• ✅ Handle exceptions inside signals — they can silently fail
5️⃣ Testing Signals
• Use @override_settings to toggle signal behavior in tests
• Use mock to track whether a signal was called
• Temporarily disconnect signals in unit tests if needed
6️⃣ Signal Pitfalls & Gotchas
• Signals don’t work with bulk operations (e.g., bulk_create)
• May execute multiple times if models are saved repeatedly
• Harder to debug in large apps if not organized
• Circular import issues if not careful with placement
7️⃣ Organizing Signals in a Large Project
• Create a separate signals.py per app
• Connect them inside apps.py under ready() method
• Avoid registering in models.py to prevent import problems
myapp/apps.py
def ready(self):
import myapp.signals
8️⃣ Alternatives to Signals
• Overriding save() and delete() methods
• Using Django middleware
• Using Celery tasks for async side effects (e.g. emails, logs)
• Pub/Sub systems (if you're going really big)
✍️ Bonus Ideas
• Compare signals with the Observer pattern in OOP
• Add a "When NOT to use signals" section
• Show an example of bad signal usage and how to improve it
Top comments (0)