Bird
0
0

Given this code snippet, what will be printed when a Comment instance is deleted?

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

@receiver(pre_delete, sender=Comment)
def before_delete(sender, instance, **kwargs):
    print(f"Deleting comment: {instance.id}")

comment = Comment.objects.get(id=1)
comment.delete()
ADeleting comment: 1
BNo output
CDeleting comment: None
DError: receiver not connected
Step-by-Step Solution
Solution:
  1. Step 1: Understand when pre_delete runs

    The before_delete function is called before the Comment instance is deleted.
  2. Step 2: Analyze the print statement

    The print outputs the instance's id, which is 1 in this case.
  3. Final Answer:

    Deleting comment: 1 -> Option A
  4. Quick Check:

    pre_delete prints before deletion [OK]
Quick Trick: pre_delete prints before instance is removed [OK]
Common Mistakes:
MISTAKES
  • Expecting output after deletion
  • Assuming instance.id is None
  • Forgetting to connect the signal

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes