George L George L - 4 years ago 184
Python Question

One to Many Relationship on same table in SQLAlchemy

I am modeling Repositories on GitHub. Each Repo can have a set of forks, of which the Repo will be the parent of.

My partial model file looks like this:

class Repo(Base):
__tablename__ = "repos"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, unique=True)
parent_id = db.Column(Integer,db.ForeignKey('repos.id'))
parent = db.relationship("Repo")


I am having trouble wrapping my head around how to properly make this relationship.

Answer Source

You can use remote_side directive

class Repo(Base):
    __tablename__ = "repos"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text, unique=True)
    parent_id = db.Column(Integer,db.ForeignKey('repos.id'))
    forks = relationship("Repo",
                backref=backref('parent', remote_side=[id])
            )

See Adjacency List Relationships documentation and this answer

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download