Performance: Why signals enable decoupled communication
This concept affects how efficiently different parts of a Django app communicate without blocking or tightly coupling code, impacting interaction responsiveness and maintainability.
Jump into concepts and practice - no test required
from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=MyModel) def send_notification_signal(sender, instance, **kwargs): send_notification(instance)
def save(self, *args, **kwargs): super().save(*args, **kwargs) # Directly call another function here send_notification(self)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct function call after save | N/A (server-side) | N/A | N/A | [X] Bad |
| Using Django signals for post-save actions | N/A (server-side) | N/A | N/A | [OK] Good |
post_save signal?signal.connect(handler, sender=Model).Book instance is saved?from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Book)
def notify(sender, instance, created, **kwargs):
if created:
print(f"New book added: {instance.title}")
book = Book(title='Django Basics')
book.save()@receiver decorator connects notify to post_save for Book.book.save()created is True for a new instance, the print statement runs with the book title.from django.db.models.signals import pre_delete
def cleanup(sender, instance):
print(f"Cleaning up {instance}")
pre_delete.connect(cleanup)**kwargs to avoid errors.**kwargs, so it will raise an error when called.**kwargs parameter in handler function -> Option D**kwargs parameter in handler function [OK]