SqlAlchemy按关系数查询和筛选



所以目前我有两个类FooBar,其中

class Foo(db.Model):
...
bars = db.relationship('Bar', backref='foo', lazy='dynamic')
...

这里,一个Foo可以有许多Bar。如何查询Foo,以便根据Bar的数量进行筛选?类似Foo.query.filter(Foo.bars.count() == x).first()

除了保留计数变量之外,还有其他方法可以做到这一点吗?

这个SQL查询将是实现它的一种方法(假设x=2(:

SELECT parent.id, COUNT(child.tid) AS num_bars 
FROM parent 
JOIN child ON parent.id = child.tid 
GROUP BY parent.id 
HAVING COUNT(child.tid) = 2;

这将转化为(sqlalchemy(:

import sqlalchemy as sa
x = 2
q = (session.query(Foo, sa.func.count(Bar.foo_id).label('num_bars'))
.join(Bar)
.group_by(Foo.id)
.having(sa.literal_column('num_bars') == x)
.from_self(Foo))

烧瓶sqlalchemy的等价物可能是

q = (db.session.query(Foo, sa.func.count(Bar.foo_id).label('num_bars'))
.join(Bar)
.group_by(Foo.id)
.having(sa.literal_column('num_bars') >= x)
.from_self(Foo))

另一种方法是使用子查询:

SELECT parent.id 
FROM parent 
WHERE (SELECT COUNT(1)
FROM child 
WHERE child.tid = parent.id
) = 2

使用SQLAlchemy:

subq = (session.query(sa.func.count(Bar.foo_id))
.filter(Bar.foo_id == Foo.id)
.scalar_subquery())
q = session.query(Foo).filter(subq == 2)

最新更新