Flask Relationships: One to Many


Example

    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(80))
        email = db.Column(db.String(120), unique=True)
        posts = db.relationship('Post', backref='user')


    class Post(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        content = db.Column(db.Text)
        user_id = db.Column(db.Integer, db.ForeignKey('user.id')

In this example we have two class the User class and the Post class, the User class will be our parent and the Post will be our post as only post can belong to one user but one user can have multiple posts. In order to achieve that we place a Foreign key on the child referencing the parent that is from our example we place a foreign key on Post class to reference the User class. We then use relationship() on the parent which we access via our SQLAlchemy object db. That then allows us to reference a collection of items represented by the Post class which is our child.

To create a bidirectional relationship we usebackref, this will allow the child to reference the parent.