SQLAlchemy order_by 公式结果

Ala*_*n S 1 python sql sql-server sqlalchemy

我是Python新手。基于这篇SO 文章,我使用 PYODBC 创建了一个 SQL 查询来搜索历史期权价格的 MSSQL 表,并选择执行值最接近我指定的所需值的期权符号。然而,我现在尝试通过重构这个程序来自学 OOP,为此我尝试在 SQLAlchemy 中实现 ORM。

我不知道如何实现计算的 Order_By 语句。我认为计算列不起作用,因为desired_strike是用户(我)在每个方法调用时指定的参数。

这是(简化的)原始代码:

import pyodbc

def get_option_symbol(stock, entry_date, exp_date, desired_strike):
    entry_date = entry_date.strftime('%Y-%m-%d %H:%M:%S')
    exp_date = exp_date.strftime('%Y-%m-%d %H:%M:%S')

    cursor.execute("""select top(1) optionsymbol 
                    from dbo.options_pricestore 
                    where underlying=? 
                    and quotedate=? 
                    and expiration=? 
                    and exchange='*' 
                    and option_type=?
                    order by abs(strike - ?)""",
                    stock, 
                    entry_date,
                    exp_date,
                    desired_strike,
                    )
    row = cursor.fetchone()  
    return row
Run Code Online (Sandbox Code Playgroud)

也许不是最 Pythonic,但它确实有效。我现在将以前的过程代码封装到类中,并使用 SQLAlchemy 的 ORM,但在这种情况下,我无法弄清楚如何在 Order_By 子句中表示 abs(strike -desired_strike)。我过去没有太多使用 lambda 函数,但这是我想到的:

import sqlalchemy

class Option(Base):
__tablename__= 'options_pricestore'
<column definitions go here>

def get_option_symbol(stock, entry_date, exp_date, desired_strike):
    entry_date = entry_date.strftime('%Y-%m-%d %H:%M:%S')
    exp_date = exp_date.strftime('%Y-%m-%d %H:%M:%S')

    qry = session.query(Option.optionsymbol).filter(and_
            (Option.underlying == stock, 
                Option.quotedate == entry_date,
                Option.expiration == exp_date,
                Option.option_type== "put",
                Option.exchange == "*")
            ).order_by(lambda:abs(Option.strike - desired_strike))

    return qry
Run Code Online (Sandbox Code Playgroud)

我收到“ArgumentError:需要 SQL 表达式对象或字符串” - 任何帮助将不胜感激。

ale*_*cxe 5

order_by想要一个字符串 - 把它给它:

qry = session.query(Option.optionsymbol).filter(and_
            (Option.underlying == stock, 
                Option.quotedate == entry_date,
                Option.expiration == exp_date,
                Option.option_type== "put",
                Option.exchange == "*")
            ).order_by('abs(strike - %d)' % desired_strike)
Run Code Online (Sandbox Code Playgroud)