0
0
Djangoframework~5 mins

Related name for reverse access in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the related_name attribute in Django models?
The related_name attribute defines the name to use for the reverse relation from the related object back to this one. It lets you access related objects easily from the other side of the relationship.
Click to reveal answer
beginner
How do you access all Book objects related to an Author if related_name='books' is set on the ForeignKey?
You can access all books of an author by using author.books.all(). The related_name 'books' creates this attribute on the Author instance.
Click to reveal answer
beginner
What happens if you do NOT set related_name on a ForeignKey in Django?
Django creates a default reverse name by using the lowercase model name with '_set' appended. For example, if the model is Book, the reverse name will be book_set.
Click to reveal answer
intermediate
Can two ForeignKey fields in different models use the same related_name?
No, related_name must be unique per model to avoid clashes in reverse relations. If two fields use the same name, Django will raise an error.
Click to reveal answer
intermediate
How does related_name='+' affect reverse access in Django?
Setting related_name='+' disables the reverse relation. This means you cannot access the related objects from the other side.
Click to reveal answer
What does related_name control in Django models?
AThe primary key field name
BThe database table name
CThe name of the reverse relation from the related model
DThe model's verbose name
If you have author = ForeignKey(Author, related_name='books'), how do you get all books of an author?
Aauthor.books.all()
Bauthor.book_set.all()
Cauthor.get_books()
Dauthor.books_set.all()
What is the default reverse name if related_name is not set?
Arelated_set
Bmodelname_set
Creverse_name
Ddefault_related
What does setting related_name='+' do?
ADisables reverse relation
BSets reverse relation to default
CCreates a reverse relation with name '+'
DRaises an error
Can two ForeignKey fields in different models share the same related_name?
AYes, always
BOnly if fields have different names
COnly if models are unrelated
DNo, it causes a conflict
Explain what related_name does in Django and why it is useful.
Think about how you get from one model to related objects in the other direction.
You got /4 concepts.
    Describe what happens if you set related_name='+' on a ForeignKey field.
    Consider when you might not want the reverse link.
    You got /4 concepts.