Bird
0
0

You want to ensure a blog post's slug field is generated from its title only if the slug is empty, before saving. Which signal and method is the best practice?

hard📝 lifecycle Q8 of 15
Django - Signals
You want to ensure a blog post's slug field is generated from its title only if the slug is empty, before saving. Which signal and method is the best practice?
AOverride the model's <code>save()</code> method to set the slug unconditionally
BUse a <code>post_save</code> signal to update the slug after saving
CUse a <code>pre_save</code> signal to check if slug is empty and set it accordingly
DUse a <code>post_delete</code> signal to set the slug before saving
Step-by-Step Solution
Solution:
  1. Step 1: Identify when to set slug

    The slug should be set before saving, and only if empty.
  2. Step 2: Choose appropriate signal

    pre_save allows modifying fields before the database save.
  3. Step 3: Avoid post_save and post_delete

    Post_save runs after saving, which may cause extra saves; post_delete is unrelated.
  4. Step 4: Overriding save() is possible but less decoupled than signals

    Signals keep logic separate and reusable.
  5. Final Answer:

    Use a pre_save signal to check if slug is empty and set it accordingly -> Option C
  6. Quick Check:

    Pre_save modifies fields before saving [OK]
Quick Trick: Set slug in pre_save only if empty [OK]
Common Mistakes:
MISTAKES
  • Using post_save causing multiple saves
  • Overwriting slug unconditionally in save()
  • Using unrelated signals like post_delete

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes