Skip to content

Instantly share code, notes, and snippets.

@robyoung
Created October 5, 2018 15:26
Show Gist options
  • Save robyoung/9d172aa98111f463d69dcdced1af4c62 to your computer and use it in GitHub Desktop.
Save robyoung/9d172aa98111f463d69dcdced1af4c62 to your computer and use it in GitHub Desktop.
sqlalchemy multiple joins
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
parent_id = db.Column(db.Integer, db.ForeignKey('person.id'), nullable=True)
other_id = db.Column(db.Integer, db.ForeignKey('person.id'), nullable=True)
house_id = db.Column(db.Integer, db.ForeignKey('house.id'), nullable=True)
mouse_id = db.Column(db.Integer, db.ForeignKey('house.id'), nullable=True)
parent = db.relationship(
'Person',
primaryjoin=id==parent_id,
remote_side=[id],
)
children = db.relationship(
'Person',
foreign_keys=[parent_id],
)
other = db.relationship(
'Person',
primaryjoin=id==other_id,
remote_side=[id],
)
others = db.relationship(
'Person',
foreign_keys=[other_id],
)
house = db.relationship(
'House',
foreign_keys=[house_id],
)
mouse = db.relationship(
'House',
foreign_keys=[mouse_id],
)
def __repr__(self):
return f'<Person id={self.id} name={self.name} parent_id={self.parent_id} other_id={self.other_id}>'
class House(db.Model):
id = db.Column(db.Integer, primary_key=True)
house_people = db.relationship('Person', foreign_keys='Person.house_id')
mouse_people = db.relationship('Person', foreign_keys='Person.mouse_id')
@robyoung
Copy link
Author

robyoung commented Oct 5, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment