SQLAlchemy不能使用功能更大作为查询中的函数

2024-05-08 21:46:37 发布

您现在位置:Python中文网/ 问答频道 /正文

来描述我的问题。可以看到以下原始sql:

select datediff(now(), create_time) > 7 as is_new from test order by is_new desc limit 19; 

我尝试通过SQLAlchemy一步一步地实现:

diff_days = func.datediff(today, test.create_time).label("diff_days")
session.query(diff_days).filter(test.id.in_((1,2,3,33344))).order_by(diff_days.asc()).all()   

这工作很好。但是当我想在mysql中描述>时。它失败了:

is_new = func.greater(func.datediff(today, test.create_time), 7).label("is_new")
session.query(is_new).filter(test.id.in_((1,2,3,33344))).order_by(is_new.asc()).all()

我知道SQLAlchemy向greater解释我的sql,而mysql不支持。那么我怎样才能用greater(a, b)这样的东西来得到我的答案呢

可能是简单的sqlselect a > b from test也能描述问题。而以上是我的本源需求。所以问题可以改变:

如何使用SQLAIchemy orm实现select a > b from test。你知道吗


Tags: fromtestnewsqlbytimeiscreate
1条回答
网友
1楼 · 发布于 2024-05-08 21:46:37

SQLAlchemy为您提供了rich operator overloading,所以就这么做吧

is_new = (func.datediff(today, test.create_time) > 7).label("is_new")
session.query(is_new).\
    filter(test.id.in_([1, 2, 3, 33344])).\
    order_by(is_new.asc()).\
    all()

这是因为创建的^{}也是^{},因此具有^{}。你知道吗

相关问题 更多 >

    热门问题