Which scenario is the best use case for Django signals?
Think about when you want to react to changes without changing the original code flow.
Django signals are best for decoupling actions that should happen automatically after certain events, like saving a model.
Consider a Django signal handler connected to the post_save signal. What happens if the handler raises an exception?
Think about how exceptions affect the flow of code execution.
If a signal handler raises an exception, it interrupts the save operation unless caught, causing errors.
Which code snippet correctly connects a post_save signal to a handler function?
from django.db.models.signals import post_save from django.dispatch import receiver from myapp.models import MyModel # Handler function here
Remember the decorator syntax and required parameters for signal handlers.
The @receiver decorator with sender specified is the cleanest and correct way to connect signals.
Given this code, why might the my_handler function not be called after saving MyModel?
from django.db.models.signals import post_save from django.dispatch import receiver from myapp.models import MyModel @receiver(post_save, sender=MyModel) def my_handler(sender, instance, **kwargs): print('Saved!') # In another file obj = MyModel() obj.save()
Think about how Django loads signal handlers and when connections are made.
If the file defining the signal handler is not imported, Django never registers the handler, so it won't be called.
Which situation is NOT a good use case for Django signals?
Consider the complexity and side effects of the task inside a signal handler.
Signals should be lightweight and fast. Complex logic with multiple queries can cause performance and debugging issues.