SQLAlchemy can't use func.bigger as func in query

空扰寡人 提交于 2021-02-08 10:01:56

问题


To desc my problem. Can see this raw sql:

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

I try to implement by SQLAlchemy step by step:

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()   

This work fine. But when I want to desc > in mysql. It failed:

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()

I know SQLAlchemy explain my sql to greater while mysql don't support. So How can I to get my answer a > b with something like greater(a, b)

May be the simple sql select a > b from test can desc the problem too. While above is my origin need. So the problem can change :

How to using SQLAIchemy orm to implement select a > b from test.


回答1:


SQLAlchemy offers you rich operator overloading, so just do

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()

This works since the created Function is also a ColumnElement and as such has ColumnOperators.



来源:https://stackoverflow.com/questions/44275354/sqlalchemy-cant-use-func-bigger-as-func-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!