Bird
0
0

What is wrong with this code snippet?

medium📝 Debug Q14 of 15
Django - Caching
What is wrong with this code snippet?
posts = Post.objects.prefetch_related('comment_set')
for post in posts:
    print(post.title, [c.text for c in post.comment_set.all()])

Assuming Comment model has a ForeignKey to Post without a related_name set.
AUsing 'comment_set' is correct; no error here
BShould use 'comments' instead of 'comment_set' in prefetch_related
CMust use select_related instead of prefetch_related for reverse relations
DThe code will raise an AttributeError because 'comment_set' is invalid
Step-by-Step Solution
Solution:
  1. Step 1: Understand default reverse relation naming

    If no related_name is set on a ForeignKey, Django uses modelname_set as the reverse relation name, here comment_set.
  2. Step 2: Check usage in prefetch_related and loop

    Using prefetch_related('comment_set') and accessing post.comment_set.all() is correct and will work without error.
  3. Final Answer:

    Using 'comment_set' is correct; no error here -> Option A
  4. Quick Check:

    Default reverse name = modelname_set [OK]
Quick Trick: Default reverse name is modelname_set if no related_name [OK]
Common Mistakes:
MISTAKES
  • Assuming related_name is always 'comments'
  • Using select_related for reverse relations
  • Expecting an error when using default reverse name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes