sqlalchemy查询:结果列名称

时间:2016-02-16 13:59:19

标签: python orm sqlalchemy

我有一个名为DevicesGpsTelemetry的模型(使用Declarative base声明)。我这样查询:

models = session.query(
    DevicesGps.ReceivedDateUtc, 
    DevicesGps.ReceivedTimeUtc,   
    DevicesGps.Latitude,                                 
    DevicesGps.Longitude)

它呈现为:

    SELECT   
    devices_gps."ReceivedDateUtc" AS "devices_gps_ReceivedDateUtc", 
    devices_gps."ReceivedTimeUtc" AS "devices_gps_ReceivedTimeUtc", 
    devices_gps."Latitude" AS "devices_gps_Latitude", 
    devices_gps."Longitude" AS "devices_gps_Longitude" 
        FROM devices_gps

我的问题:如何将AS语句之后的名称(如"gps_telemetry_ReceivedDateUtc")更改为我想要的名称?

背景:这些名称对我很重要,因为我使用此查询pandas.read_sql并且名称成为DataFrame的列名称

1 个答案:

答案 0 :(得分:3)

在每列之后添加.label('desired_name')。在你的情况下,它看起来像

models = session.query(
    DevicesGps.ReceivedDateUtc.label("gps_telemetry_ReceivedDateUtc"), 
    DevicesGps.ReceivedTimeUtc.label("gps_telemetry_ReceivedTimeUtc"),   
    DevicesGps.Latitude.label("gps_telemetry_Latitude"),                                 
    DevicesGps.Longitude.label("gps_telemetry_Longitude")
)