Bird
0
0

Consider this Django code snippet:

medium📝 Predict Output Q4 of 15
Django - Signals
Consider this Django code snippet:
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Book(models.Model):
    title = models.CharField(max_length=100)

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

book = Book(title='Django Unchained')
book.save()

What will be printed when the above code runs?
ABook updated: Django Unchained
BNew book created: Django Unchained
CNo output will be printed
DAn error will occur because 'created' is missing
Step-by-Step Solution
Solution:
  1. Step 1: Understand post_save signal parameters

    The post_save signal passes a created boolean indicating if the instance was created or updated.
  2. Step 2: Analyze the handler logic

    If created is True, it prints "New book created: ..."; otherwise, it prints "Book updated: ...".
  3. Step 3: Execution flow

    Since book.save() is called on a new instance, created will be True.
  4. Final Answer:

    New book created: Django Unchained -> Option B
  5. Quick Check:

    New instance triggers created=True [OK]
Quick Trick: Created=True means new instance saved [OK]
Common Mistakes:
MISTAKES
  • Assuming created is always False
  • Forgetting to include 'created' parameter
  • Expecting no output on save

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes