今天我遇到了sqlalchemy查询的问题。我已经尝试了一段时间,但我无法弄清楚我做错了什么。 我对sqlalchemy的整个故事都很陌生,我开始对中等简单查询感到满意,但我无法解决以下问题:
units = Unit.query.join(Campaign).join(ServedUnitMetric, and_(ServedUnitMetric.client_id == clientID)).filter(
(Campaign.active_applications.any(and_(ActiveApplication.application_id == client.application_id, ActiveApplication.enabled == True))) &
(Campaign.targeting_setting.has(TargetingSetting.countries.any(and_(Country.country_code == client.locale.country_code, Country.is_active == True)))) &
(Campaign.expiration_date > datetime.utcnow()) &
(Campaign.active_campaign.has(ActiveCampaign.expenses + item.price <= Campaign.budget)) &
(Campaign.active_campaign.has(ActiveCampaign.status == CAMPAIGN_STATUS_ACTIVE)) &
(Campaign.max_bid >= item.price) &
(Unit.serve_setting.has(and_(ServeSetting.language_code == client.locale.language_code, ServeSetting.valid_from <= datetime.utcnow(), ServeSetting.valid_to >= datetime.utcnow()))) &
(
((Unit.serve_setting.has(ServeSetting.serve_once_per_period == True)) & (ServedUnitMetric.unit_id != Unit.id)) |
((Unit.serve_setting.has(ServeSetting.serve_once_per_period == True)) & (ServedUnitMetric.unit_id == Unit.id) & (datetime.utcnow() > (ServedUnitMetric.endDate + ServeSetting.period_hours)))
)
)
查询的第一部分正在运行,现在我正试图让第二部分工作,但我仍然遇到问题。 它总是返回空数据,但我已经准备好了测试,我确信它应该返回数据。
我收到了错误,但我仍然不知道如何解决它。问题出现在这里
ServedUnitMetric.endDate + ServeSetting.period_hours
看起来SQLAlchemy没有正确翻译 DateTime + Interval 。它看起来这句话被翻译成双重值。现在就是了解如何将DateTime添加到Interval中,并且应该完成这个技巧。 我正在尝试使用 func.adddate ,但它继续溢出,我想是因为Interval是1970-1-1 +您输入的间隔。
由于https://stackoverflow.com/a/17236032/956541
,我终于找到了一个似乎有效的解决方案这条线变为:
((Unit.serve_setting.has(ServeSetting.serve_once_per_period == True)) &安培; (ServedUnitMetric.unit_id == Unit.id)&amp; (func.abs(func.unix_timestamp(datetime.utcnow()) - func.unix_timestamp(ServedUnitMetric.endDate))&gt; = (ServeSetting.period_hours * 60 * 60)))
感谢您的帮助,
恩里科
答案 0 :(得分:0)
解决方案是func.timestamp(date)
((Unit.serve_setting.has(ServeSetting.serve_once_per_period == True)) & (ServedUnitMetric.unit_id == Unit.id) & (func.abs(func.unix_timestamp(datetime.utcnow()) - func.unix_timestamp(ServedUnitMetric.endDate)) >= (ServeSetting.period_hours * 60 * 60)))