本文介绍了构造查询以对与给定A实例相关的所有B实例进行多对多过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取与特定TableA
实例相关的所有TableB
实例.这是一个多对多的关系.如何构造此查询?
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))
)
推荐答案
使用关系的 contains
方法以过滤与TableA项相关的TableB项.
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))
或者如果要考虑大量数据的性能,请使用join
和filter
.
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)
这篇关于构造查询以对与给定A实例相关的所有B实例进行多对多过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!