Recall & Review
beginner
What is a ForeignKey in Django?
A ForeignKey in Django is a field used to create a one-to-many relationship between two models. It links one model to another by storing the primary key of the related model.
Click to reveal answer
beginner
How do you define a one-to-many relationship using ForeignKey in Django models?
You add a ForeignKey field in the 'many' side model pointing to the 'one' side model. For example, in a Blog and Entry setup, Entry has a ForeignKey to Blog.
Click to reveal answer
intermediate
What does the 'on_delete' parameter do in a ForeignKey field?
The 'on_delete' parameter defines what happens to related objects when the referenced object is deleted. Common options are CASCADE (delete related), SET_NULL (set to null), and PROTECT (prevent deletion).
Click to reveal answer
intermediate
How can you access all related objects from the 'one' side in a one-to-many ForeignKey relationship?
You use the reverse relation manager. By default, Django creates a manager named <modelname>_set. For example, blog.entry_set.all() returns all entries for a blog.
Click to reveal answer
beginner
Why is using ForeignKey better than storing IDs manually for relationships?
ForeignKey ensures data integrity, provides easy querying, and integrates with Django's ORM features like automatic joins and reverse lookups, making code cleaner and safer.
Click to reveal answer
In Django, which model should have the ForeignKey field in a one-to-many relationship?
✗ Incorrect
The ForeignKey is placed on the 'many' side model to link it to the 'one' side model.
What does the 'on_delete=models.CASCADE' option do in a ForeignKey?
✗ Incorrect
CASCADE deletes all related objects automatically when the referenced object is deleted.
How do you access all related objects from the 'one' side in a ForeignKey relationship?
✗ Incorrect
Django automatically creates a reverse manager named _set to access related objects.
Which of these is NOT a valid 'on_delete' option in Django ForeignKey?
✗ Incorrect
'IGNORE' is not a valid on_delete option in Django.
Why is using ForeignKey preferred over manually storing IDs for relationships?
✗ Incorrect
ForeignKey helps maintain data integrity and provides easy querying and reverse lookups.
Explain how to create a one-to-many relationship using ForeignKey in Django models.
Think about which model holds the ForeignKey and what happens on deletion.
You got /4 concepts.
Describe how to access related objects from the 'one' side in a ForeignKey relationship in Django.
Remember Django creates a manager automatically for reverse lookups.
You got /4 concepts.