简体   繁体   中英

How to use SQLAlchemy addcolumn to include a func.count value

I have 2 tables,let's call them A and B. A has some information about each user, and B has some services of users. Here I want to use SQLAlchemy to query the user and count of their services.

--------
A:
username(primary key),
age,
full_name,
password
B:
username,
service_name
--------

I can use session.query(A).filter(A.username.like('foo%')) to query users,but I cannot add the sum column.

I'm not sure if there is a more permanent way of attaching the count to the objects but this will let you get the count and the objects at the same time.

from sqlalchemy.sql import func
query = session.query(A, func.count(B.service_name))
query = query.outerjoin(B, A.username == B.username)
query = query.group_by(A.username).filter(A.username.like('foo%'))
for (user, user_service_count) in query.all():
    print(user, user_service)

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