Hint: Parent points to another instance; print its name [OK]
Common Mistakes:
Expecting 'Child' instead of 'Root'
Assuming parent is None
Thinking it causes an error
4. What is wrong with this self-referencing model code?
class Employee(models.Model):
name = models.CharField(max_length=100)
manager = models.ForeignKey(Employee, null=True, blank=True, on_delete=models.SET_NULL)
medium
A. ForeignKey should use 'self' as a string, not the class name directly.
B. on_delete=models.SET_NULL is invalid for ForeignKey.
C. null=True and blank=True cannot be used together.
D. CharField must have unique=True for self-reference.
Solution
Step 1: Check ForeignKey target
For self-reference, use 'self' as a string, not the class name directly.
Step 2: Validate other parameters
on_delete=models.SET_NULL and null=True, blank=True are valid here.
Final Answer:
ForeignKey should use 'self' as a string, not the class name directly. -> Option A
Quick Check:
Use 'self' string in ForeignKey for self-reference [OK]
Hint: Use 'self' string in ForeignKey, not class name directly [OK]
Common Mistakes:
Using class name instead of 'self' string
Thinking on_delete=models.SET_NULL is invalid
Confusing null and blank usage
5. You want to create a Django model for a comment system where each comment can reply to another comment. Which is the best way to model this self-referencing relationship?
hard
A. Use a ForeignKey to another model called Reply.
B. Use a ManyToManyField to 'self' to link replies.
C. Use a OneToOneField to 'self' to link each comment to one reply.
D. Use a ForeignKey to 'self' with null=True and blank=True to allow top-level comments.
Solution
Step 1: Understand comment-reply structure
Each comment can optionally reply to one other comment or none (top-level).
Step 2: Choose correct field type
ForeignKey to 'self' with null=True and blank=True allows optional parent comment.
Step 3: Evaluate other options
ManyToManyField allows multiple parents, OneToOneField limits to one reply, and another model is unnecessary.
Final Answer:
Use a ForeignKey to 'self' with null=True and blank=True to allow top-level comments. -> Option D