Performance: Receiver decorator
This affects the event handling and signal processing speed in Django applications, impacting responsiveness during runtime.
Jump into concepts and practice - no test required
from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save) def my_handler(sender, **kwargs): print('Signal received')
from django.db.models.signals import post_save from django.dispatch import Signal def my_handler(sender, **kwargs): print('Signal received') post_save.connect(my_handler)
| Pattern | Signal Connections | Duplicate Calls | CPU Usage | Verdict |
|---|---|---|---|---|
| Manual connect() calls in multiple places | Multiple | Yes | High | [X] Bad |
| Using @receiver decorator once per handler | Single | No | Low | [OK] Good |
@receiver decorator in Django?@receiver decorator@receiver decorator for the post_save signal of a model named Book?@receiver decorator takes the signal as first argument and sender=ModelName as keyword argument.sender, instance, and **kwargs.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, **kwargs):
print(f"Book saved: {instance.title}")
book = Book(title='Django Basics')
book.save()@receiver decorator connects notify to post_save for Book.book.save()?post_save, calling notify, which prints the book's title.from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Author)
def handle_save(instance, **kwargs):
print(f"Author saved: {instance.name}")sender, instance, and **kwargs.handle_save lacks the sender parameter, causing an error.sender parameter in function definition -> Option BUser model instance is created (not updated). How do you use the @receiver decorator with post_save to achieve this?created flag in post_savepost_save signal passes a created boolean indicating if the instance was newly created.created to run code only on creationif created: inside the receiver function to run code only when a new instance is created.