You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLAlchemy中获取实体列的指定名称用于自定义语句?

SQLAlchemy实体获取列名的方法

当然可以!你提到的ReportMetadataEntity.id.name就是最直接的方式,能精准拿到你在Column定义里指定的name参数值,比如这里的"id"或者"application_customer_id"。

除了这种直接访问列属性的方式,还有另一种常用方法:通过模型的__table__属性来获取列名,比如:

ReportMetadataEntity.__table__.c.id.name

这种方式在需要批量遍历模型所有列名的时候会更方便。

举个实际用在自定义SQL里的例子:

from sqlalchemy import text

# 获取列名
id_col = ReportMetadataEntity.id.name
customer_id_col = ReportMetadataEntity.application_customer_id.name

# 拼接自定义SQL
custom_sql = text(f"SELECT {id_col}, {customer_id_col} FROM reports_metadata WHERE {customer_id_col} = :customer_id")

这样写的好处是不用硬编码列名,后续如果修改数据库列名,只要在模型的Column定义里改name参数,代码里的引用会自动同步,减少维护成本。

内容的提问来源于stack exchange,提问作者No Such Agency

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:48:14