Using a SQLAlchemy Integer field to create a timedelta object for filtering

☆樱花仙子☆ 提交于 2020-01-10 04:15:35

问题


I have an object called Item. It has 2 fields: a datetime row called "created_on," and an integer row called "days."

I want to query for all objects that were created "days" many days ago.

Here's how I thought it should be done:

now = utcnow()
session.query(Item).filter(Item.created_on + Interval(timedelta(days=Item.days)) <= now)

But I'm unable to create a timedelta like this. I'm getting this error:

TypeError: unsupported type for timedelta minutes component: InstrumentedAttribute

Update:

Thanks to van, I should be using a built-in function. I'm using Mysql 5.1, so it would be timestampadd. My new query is this:

now = utcnow()
session.query(Item).filter(func.timestampadd('DAY', Item.days, Item.created_on) <= now)

However, the new error I'm getting is:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''DAY', items.days, items.created_on) <= '2015-07-12 ' at line 3

回答1:


I do not think that Interval will help you there, as it would not be able to coerce into DB-specific date[time] functions. So you should probably use the platform specific date[time] functions to solve this.

If you are using postgresql, the code below should work (assuming Items.days is integer):

q = (session.query(Item)
     .filter(func.age(now, Item.created_on) <=
             func.make_interval(0, 0, 0, Item.days)
             )
     )

See postgres' Date/Time Functions and Operators for more information.




回答2:


now = utcnow()
session.query(Item).filter(Item.created_on + func.make_interval(0, 0, 0, Item.days) <= now)


来源:https://stackoverflow.com/questions/31362484/using-a-sqlalchemy-integer-field-to-create-a-timedelta-object-for-filtering

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