Junior — Middle
Can you explain how signals work in Django and how they interact with models and other framework components?
sobes.tech AI
Answer from AI
In Django, signals are a mechanism that allows application components to respond to certain events without creating tight couplings between them. They are used to notify about events such as creation, update, or deletion of model objects.
Key points of signals operation:
- Signal definition: Django provides built-in signals, such as
pre_save,post_save,pre_delete,post_delete. - Subscribing to a signal: using the
@receiverdecorator or theconnectfunction, you can subscribe a handler (slot) to a signal. - Signal handler: a function that executes when the signal is triggered, receiving information about the event and the object.
Example of using a signal for a model:
from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import MyModel
@receiver(post_save, sender=MyModel)
def mymodel_post_save(sender, instance, created, **kwargs):
if created:
print(f'New object created: {instance}')
else:
print(f'Object updated: {instance}')
Thus, signals allow separating the reaction logic to events from the main business logic, improving modularity and extensibility of the application.