问题
I want to get all TableB instances that are related to a specific TableA instance. It is a many-to-many relationship. How do I construct this query?
class TableA(db.Model):
__tablename__ = 'tableA'
id = db.Column(db.Integer, primary_key=True)
class TableB(db.Model):
__tablename__ = 'tableB'
id = db.Column(db.Integer, primary_key=True)
many_to_many = db.relationship(TableA, secondary='association_table')
association_table = db.Table('association',
db.Column('tableA_id', db.Integer, db.ForeignKey(TableA.id)),
db.Column('tableB_id', db.Integer, db.ForeignKey(TableB.id))
)
回答1:
Use the relationship's contains method to filter TableB items that are related to the TableA item.
session.query(TableB).filter(TableB.many_to_many.contains(eleA))
Or use any to perform more complex filters on the relationship.
# for example, all B's related to A's with id < 10
session.query(TableB).filter(TableB.many_to_many.any(TableA.id < 10))
Or if performance over a very large set of data is a concern, use join and filter.
session.query(TableB).join(TableB.many_to_many).filter(TableA.id == eleA.id)
来源:https://stackoverflow.com/questions/31839150/construct-a-query-to-filter-many-to-many-for-all-b-instances-related-to-a-given