Bird
0
0

Given this code, what will be printed when a new instance of MyModel is saved?

medium📝 component behavior Q4 of 15
Django - Signals
Given this code, what will be printed when a new instance of MyModel is saved?
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, **kwargs):
    print(f"Saved: {instance}")

obj = MyModel()
obj.save()
ASaved: <MyModel object>
BNothing is printed
CError: receiver not connected
DSaved: None
Step-by-Step Solution
Solution:
  1. Step 1: Understand the @receiver decorator

    The decorator connects my_handler to post_save signal for MyModel, so it runs after save.
  2. Step 2: Analyze what happens on obj.save()

    Saving obj triggers post_save, calling my_handler, which prints the instance representation.
  3. Final Answer:

    Saved: <MyModel object> -> Option A
  4. Quick Check:

    post_save triggers print with instance [OK]
Quick Trick: post_save calls receiver after save, printing instance [OK]
Common Mistakes:
MISTAKES
  • Assuming no output without explicit call
  • Thinking decorator does not connect receiver
  • Expecting None instead of instance print

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes