SQLAlchemy再次过滤查询

时间:2018-02-22 11:50:27

标签: python mysql python-3.x sqlalchemy subquery

我想计算每个类别中用户的建筑物数量。

我的查询非常类似:

q = session.query(buildings, category_buildings)\
           .join(category_buildings, category_buildings.id == buildings.category)\
           .filter(buildings.builder_id == user_id)

for cid in range(1, category_count):
    q.filter(category_buildings.id == cid)
    buildings_for_cid = q.all()

for循环中的q.filter()并没有给出我想要的结果,因为它根本没有按类别ID进行过滤。我该怎么办?

在纯SQL中:( AND C.id = INT将在for循环中发生)

SELECT * FROM buildings B
JOIN category_buildings C ON B.category = C.id
WHERE builder_id = 1
AND C.id = 1

1 个答案:

答案 0 :(得分:1)

当您运行q.all()时,您实际上只是运行第一行查询,最后使用.all(),因为您应用的第二个过滤器未存储为q。

基本上你这样做了:

q = 'abc'
for cid in range(1, 10):
   q.upper()
   print(q)

您希望q成为'ABC',但它实际上从未被修改过。我认为你真正想做的是:

q = session.query(buildings, category_buildings) \
    .join(category_buildings, category_buildings.id == buildings.category) \
    .filter(buildings.builder_id == user_id)

for cid in range(1, category_count):
    branched = q.filter(category_buildings.id == cid)
    buildings_for_cid = branched.all()