找到你要的答案

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

Q:如何使用SQLAlchemy addcolumn包括func.count价值

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 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
--------

我可以使用会话。查询(一)。滤波器(a.username。像('foo %))查询用户,但我无法添加和柱。

answer1: 回答1:

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)

我不知道是否有一个更持久的方式附加计数的对象,但这将让你得到的计数和对象在同一时间。

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)
python  sqlalchemy