我有一个名为 Item 的对象。它有 2 个字段:一个名为“created_on”的日期时间行和一个名为“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
不会帮助你,因为它不能强制转换为特定于数据库的日期 [时间] 函数。因此,您可能应该使用特定于平台的日期[时间] 函数来解决这个问题。
如果您使用的是 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了解更多信息。
关于python - 使用 SQLAlchemy Integer 字段创建用于过滤的 timedelta 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31362484/