简体   繁体   中英

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. What do I do?

In plain SQL: (the AND C.id = INT would happen in the for loop)

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.

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. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM