我有一个叫做item的对象。它有两个字段:名为“created_on”的datetime行和名为“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特定的日期[时间]函数。因此,您可能应该使用特定于平台的日期[时间]函数来解决这个问题。
如果您使用的是postgresql,下面的代码应该可以工作(假设Items.days是整数):

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

有关详细信息,请参见postgres'Date/Time Functions and Operators

10-07 13:23
查看更多