在渲染模板时如何从sqlalchemy引用自定义字段?

时间:2012-11-09 19:24:17

标签: python sqlalchemy pyramid mako

我正在尝试打印func.count()调用的值,但是一旦我进入我的mako模板,我就无法弄清楚它是如何命名的。我试图在调试器行中对变量进行pprint和dict,但是它们作为对象返回,所以我不确定从这里开始。

这是我正在执行的视图的代码:


    TodayList = DBSession.query(
    func.count(ExtendedCDR.uniqueid),ExtendedCDR,ExtensionMap)
    .filter(or_(
         ExtensionMap.exten == ExtendedCDR.extension,
         ExtensionMap.prev_exten == ExtendedCDR.extension))
    .filter(ExtendedCDR.start > func.curdate())
    .group_by(ExtendedCDR.extension)
    .order_by(func.count(ExtendedCDR.uniqueid).desc())
    .all()

当此代码运行时,sql查询的调试将返回:

2012-11-09 19:16:10,392 INFO [sqlalchemy.engine.base.Engine][Dummy-3] SELECT count(cdr_extended.uniqueid) AS count_1, cdr_extended.uniqueid AS cdr_extended_uniqueid, cdr_extended.start AS cdr_extended_start, cdr_extended.end AS cdr_extended_end, cdr_extended.clid AS cdr_extended_clid, cdr_extended.src AS cdr_extended_src, cdr_extended.dst AS cdr_extended_dst, cdr_extended.dcontext AS cdr_extended_dcontext, cdr_extended.channel AS cdr_extended_channel, cdr_extended.dstchannel AS cdr_extended_dstchannel, cdr_extended.lastapp AS cdr_extended_lastapp, cdr_extended.lastdata AS cdr_extended_lastdata, cdr_extended.duration AS cdr_extended_duration, cdr_extended.billsec AS cdr_extended_billsec, cdr_extended.disposition AS cdr_extended_disposition, cdr_extended.amaflags AS cdr_extended_amaflags, cdr_extended.accountcode AS cdr_extended_accountcode, cdr_extended.userfield AS cdr_extended_userfield, cdr_extended.extension AS cdr_extended_extension, concat(concat(ext_map.FName, %s), ext_map.LName) AS anon_1, ext_map.exten AS ext_map_exten, ext_map.FName AS ext_map_FName, ext_map.LName AS ext_map_LName, ext_map.login_name AS ext_map_login_name, ext_map.isManager AS ext_map_isManager, ext_map.prev_exten AS ext_map_prev_exten FROM cdr_extended, ext_map WHERE (ext_map.exten = cdr_extended.extension OR ext_map.prev_exten = cdr_extended.extension) AND cdr_extended.start > curdate() GROUP BY cdr_extended.extension ORDER BY count(cdr_extended.uniqueid) DESC

这是我的mako模板代码:

FName

然而,Mako抛出了$ {topentry.count_1}不存在的异常,尽管人们会认为它会给出上面的DEBUG输出。

有谁知道我如何根据python / Mako查找count_1的名称?

2 个答案:

答案 0 :(得分:2)

您应该能够使用.label()为查询命名返回值。例如,DBSession.query(func.count(ExtendedCDR.unique_id).label('count'), ...)

答案 1 :(得分:0)

count_1不属于您的对象,它是为计数func.count()提取的,它不是您对象的一行。您需要了解SQLAlchemy对该值的真正作用。