[英]SQLAlchemy filter query again
I want to count a users amount of buildings in each category.我想计算每个类别中用户的建筑物数量。
I have a query very much like this:我有一个非常像这样的查询:
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()
The q.filter() inside the for loop doesn't give me the desired result, as it doesnt filter by category id at all. for 循环内的 q.filter() 没有给我想要的结果,因为它根本不按类别 id 过滤。 What do I do?
我该怎么办?
In plain SQL: (the AND C.id = INT would happen in the for loop)在普通 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
When you run q.all()
you were essentially just running the first-line query, with .all()
on the end, because the second filter you applied wasn't stored as q.当您运行
q.all()
你基本上只是在运行第一行查询,用.all()
就完了,因为你应用了第二过滤器没有被存储为q。
So essentially you did this:所以基本上你这样做了:
q = 'abc'
for cid in range(1, 10):
q.upper()
print(q)
You're expecting q
to be 'ABC'
but it never actually gets modified.你期望
q
是'ABC'
但它实际上从未被修改过。 What I think you actually want to do is:我认为你真正想做的是:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.