Construct a query to filter many-to-many for all B instances related to a given A instance

≯℡__Kan透↙ 提交于 2019-12-11 10:29:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!