Bird
0
0

Given this code snippet, what will be printed when a new Book instance is created?

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

@receiver(post_save, sender=Book)
def announce_book(sender, instance, created, **kwargs):
    if created:
        print(f"New book added: {instance.title}")

book = Book.objects.create(title='Django Basics')
ANew book added:
BNew book added: Django Basics
CNo output
DError: missing argument
Step-by-Step Solution
Solution:
  1. Step 1: Understand the signal and handler

    The post_save signal triggers after saving a model. The handler checks if created is True, meaning a new record.
  2. Step 2: Analyze the code execution

    Creating a new Book instance sets created=True, so the print statement runs with the title.
  3. Final Answer:

    New book added: Django Basics -> Option B
  4. Quick Check:

    post_save with created=True prints title [OK]
Quick Trick: Check 'created' flag to print on new records only [OK]
Common Mistakes:
MISTAKES
  • Ignoring the 'created' flag
  • Assuming no output on create
  • Confusing signal arguments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes