Python SQLAlchemy:如何编译像sql.func.std这样的函数

Python SQLAlchemy:如何编译像sql.func.std这样的函数,python,sqlalchemy,Python,Sqlalchemy,我想对sql.func.std进行一些小更改 当std result为nan时,我想返回一个不同的值 使用此代码: from sqlalchemy.sql.expression import FunctionElement class std(FunctionElement): name = 'std' @compiles(std) def compile(element, compiler, **kw): elem = compiler.process(element.c

我想对sql.func.std进行一些小更改 当std result为nan时,我想返回一个不同的值

使用此代码:

from sqlalchemy.sql.expression import FunctionElement

class std(FunctionElement):
    name = 'std'


@compiles(std)
def compile(element, compiler, **kw):
    elem = compiler.process(element.clauses)
    return "if(isnan(std(%s)), 0, std(%s))" % (elem, elem)


t1 = sql.select([sql.literal("1").label('a')]).alias('t1')

q = sql.select([std(t1.c.a)]).select_from(t1)
结果如预期

SELECT if(isnan(std(t1.a)), 0, std(t1.a)) FROM (SELECT '1' AS a) AS t1
使用此查询时

q = sql.select([sql.func.std(t1.c.a)]).select_from(t1)
结果是错误的

SELECT std(t1.a) AS std_1 FROM (SELECT '1' AS a) AS t1

如果您希望注册可从中访问的通用函数,则应基于函数,而不是
FunctionElement

In [6]: from sqlalchemy.sql.functions import GenericFunction
   ...: 
   ...: class std(GenericFunction):
   ...:     name = 'std'
   ...: 

In [8]: q = select([func.std(t1.c.a)]).select_from(t1)

In [9]: print(q)
SELECT if(isnan(std(t1.a)), 0, std(t1.a)) AS std_1 
FROM (SELECT :param_1 AS a) AS t1