我有一个名为Item的对象。它有两个字段:一个名为"created_on"的日期时间行和一个名为"days"的整数行。"
我想查询在"days"前创建的所有对象。
我认为应该这样做:
now = utcnow()
session.query(Item).filter(Item.created_on + Interval(timedelta(days=Item.days)) <= now)
但是我不能创建这样的时间增量。我得到这个错误:
TypeError: unsupported type for timedelta minutes component: InstrumentedAttribute
更新:多亏了van,我应该使用内置函数。我使用Mysql 5.1,所以它将是timestampadd
。我的新查询是:
now = utcnow()
session.query(Item).filter(func.timestampadd('DAY', Item.days, Item.created_on) <= now)
然而,我得到的新错误是:
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
我不认为Interval
会在那里帮助您,因为它将无法强制转换为特定于db的日期[时间]函数。所以你可能应该使用平台特定的日期[时间]函数来解决这个问题。
Items.days
是整数):
q = (session.query(Item)
.filter(func.age(now, Item.created_on) <=
func.make_interval(0, 0, 0, Item.days)
)
)
详细信息请参见postgres'
日期/时间函数和操作符
now = utcnow()
session.query(Item).filter(Item.created_on + func.make_interval(0, 0, 0, Item.days) <= now)