Created
October 5, 2018 15:26
-
-
Save robyoung/9d172aa98111f463d69dcdced1af4c62 to your computer and use it in GitHub Desktop.
sqlalchemy multiple joins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://docs.sqlalchemy.org/en/latest/orm/join_conditions.html