0
0
Djangoframework~10 mins

Self-referencing relationships in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a self-referencing ForeignKey in a Django model.

Django
class Category(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey('[1]', on_delete=models.CASCADE, null=True, blank=True)
Drag options to blanks, or click blank then click option'
A'Category'
B'self'
C'models'
D'parent'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the model class name directly without quotes.
Using an unrelated string instead of 'self'.
2fill in blank
medium

Complete the code to allow a Category to have many children categories.

Django
class Category(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name=[1])
Drag options to blanks, or click blank then click option'
A'children'
B'parents'
C'siblings'
D'categories'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parents' which is the opposite direction.
Using unrelated names like 'siblings'.
3fill in blank
hard

Fix the error in the model field to correctly allow null parent categories.

Django
parent = models.ForeignKey('self', on_delete=models.CASCADE, [1]=True, blank=True, related_name='children')
Drag options to blanks, or click blank then click option'
Aallow_null
Bempty
Cnull
Dnullable
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'nullable' instead of 'null'.
Confusing 'blank' with 'null'.
4fill in blank
hard

Fill both blanks to create a self-referencing ManyToManyField with a symmetrical relationship.

Django
class Person(models.Model):
    name = models.CharField(max_length=100)
    friends = models.[1]('self', [2]=True, blank=True)
Drag options to blanks, or click blank then click option'
AManyToManyField
BForeignKey
Csymmetrical
Drelated_name
Attempts:
3 left
💡 Hint
Common Mistakes
Using ForeignKey instead of ManyToManyField.
Forgetting to set symmetrical=True for self-referencing many-to-many.
5fill in blank
hard

Fill all three blanks to define a self-referencing ManyToManyField with an asymmetrical relationship and a custom reverse name.

Django
class Employee(models.Model):
    name = models.CharField(max_length=100)
    mentors = models.[1]('self', symmetrical=[2], [3]='mentees', blank=True)
Drag options to blanks, or click blank then click option'
AManyToManyField
BFalse
Crelated_name
DTrue
Attempts:
3 left
💡 Hint
Common Mistakes
Setting symmetrical=True for an asymmetrical relation.
Not providing a related_name for reverse access.
Using ForeignKey instead of ManyToManyField.