Complete the code to define a one-to-many relationship in Flask-SQLAlchemy.
class Parent(db.Model): id = db.Column(db.Integer, primary_key=True) children = db.relationship('[1]', backref='parent')
The db.relationship function takes the name of the related model class as a string. Here, the child model is named Child.
Complete the code to define the foreign key in the child model.
class Child(db.Model): id = db.Column(db.Integer, primary_key=True) parent_id = db.Column(db.Integer, db.ForeignKey('[1]'))
The foreign key references the parent table and column as a string in the format tablename.columnname. The table name is usually lowercase, so parent.id is correct.
Fix the error in the relationship definition to enable lazy loading.
class Parent(db.Model): id = db.Column(db.Integer, primary_key=True) children = db.relationship('Child', [1]='dynamic')
backref or foreign_key instead of lazy.The lazy parameter controls how related items are loaded. Setting lazy='dynamic' enables query-based loading.
Fill both blanks to define a back reference and enable cascade delete.
class Parent(db.Model): id = db.Column(db.Integer, primary_key=True) children = db.relationship('Child', backref=[1], cascade=[2])
The backref creates a reverse attribute named parent on the child. The cascade option 'all, delete-orphan' ensures children are deleted when the parent is deleted.
Fill all three blanks to create a dictionary comprehension mapping child names to their ages for children older than 5.
child_ages = {child.[1]: child.[2] for child in parent.children if child.[3] > 5}This comprehension creates a dictionary where keys are child names and values are their ages, but only for children older than 5.