0
0
Flaskframework~5 mins

Relationships (one-to-many) in Flask - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a one-to-many relationship in Flask SQLAlchemy?
It means one record in a table can be linked to many records in another table. For example, one author can have many books.
Click to reveal answer
beginner
How do you define a one-to-many relationship in Flask SQLAlchemy models?
Use db.relationship() on the "one" side and db.ForeignKey() on the "many" side to link tables.
Click to reveal answer
intermediate
What does the backref parameter do in a one-to-many relationship?
It creates a shortcut to access the "one" side from the "many" side. For example, from a book, you can get its author easily.
Click to reveal answer
intermediate
Why is it important to use lazy='dynamic' in relationships?
It delays loading related items until needed, which helps performance when you have many related records.
Click to reveal answer
beginner
Show a simple example of a one-to-many relationship between Author and Book models in Flask SQLAlchemy.
class Author(db.Model):<br> &nbsp;&nbsp;id = db.Column(db.Integer, primary_key=True)<br> &nbsp;&nbsp;name = db.Column(db.String(50))<br> &nbsp;&nbsp;books = db.relationship('Book', backref='author', lazy='dynamic')<br><br>class Book(db.Model):<br> &nbsp;&nbsp;id = db.Column(db.Integer, primary_key=True)<br> &nbsp;&nbsp;title = db.Column(db.String(100))<br> &nbsp;&nbsp;author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
Click to reveal answer
In Flask SQLAlchemy, which side uses db.ForeignKey in a one-to-many relationship?
ABoth sides
BThe "many" side
CThe "one" side
DNeither side
What does the backref argument in db.relationship() create?
AA new table
BA validation rule
CA database index
DA shortcut to access the related object from the other side
Which of these is a benefit of using lazy='dynamic' in relationships?
AImproves performance by loading related records only when needed
BLoads all related records immediately
CPrevents any related records from loading
DAutomatically deletes related records
In a one-to-many relationship, how do you access all books of an author named author?
Aauthor.get_books()
Bauthor.book_id
Cauthor.books
Dauthor.books_id
What type of database column is used to link the 'many' side to the 'one' side?
AForeign key
BPrimary key
CUnique key
DIndex
Explain how to set up a one-to-many relationship between two models in Flask SQLAlchemy.
Think about how one author can have many books and how to link them in code.
You got /4 concepts.
    Describe the role of the 'lazy' parameter in Flask SQLAlchemy relationships and why it matters.
    Consider how loading data only when needed helps your app run faster.
    You got /4 concepts.