Bird
0
0

Given this code snippet, what will be printed when a new Author instance is saved?

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

@receiver(pre_save, sender=Author)
def before_save(sender, instance, **kwargs):
    print('Before saving:', instance.name)

@receiver(post_save, sender=Author)
def after_save(sender, instance, created, **kwargs):
    if created:
        print('Created:', instance.name)
    else:
        print('Updated:', instance.name)

# Assume instance.name = 'Alice' and this is a new save
AUpdated: Alice
BCreated: Alice Before saving: Alice
CBefore saving: Alice Created: Alice
DBefore saving: Alice Updated: Alice
Step-by-Step Solution
Solution:
  1. Step 1: Understand signal order on save

    pre_save runs before saving, so it prints 'Before saving: Alice' first.
  2. Step 2: Check post_save behavior for new instance

    post_save runs after saving; since created=True, it prints 'Created: Alice'.
  3. Final Answer:

    Before saving: Alice Created: Alice -> Option C
  4. Quick Check:

    pre_save then post_save with created=True = Before saving: Alice Created: Alice [OK]
Quick Trick: pre_save prints first, post_save with created=True prints second [OK]
Common Mistakes:
MISTAKES
  • Assuming post_save runs before pre_save
  • Ignoring the created flag in post_save
  • Mixing update and create messages

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes