问题
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