如何在相同列名的情况下在sqlalchemy查询中连接不同的表?

16 投票
1 回答
7299 浏览
提问于 2025-04-18 16:03

表的描述如下:

License: id, customer_id, product_id, expires_at
Customer: id, name
Product: id, name

我这样查询:

result = session.\
            query(License.id, License.customer_id, License.product_id, License.status, License.expires_at,\
                  Customer.name,\
                  Product.name).\
            # some filtering on those columns (JOIN conditions)
            all()

我希望连接后的表包含:

License.id, Customer.name, Product.name

现在我得到的 result 是一系列 KeyedTuples。我该如何从中访问所需的列呢?比如 result[0].name 只给出了 Customer.name,那么我该如何获取 Product.name 呢?

1 个回答

20

使用 label 方法:

Customer.name.label("Customer_name"),\
Product.name.label("Product_name").\

撰写回答