今天,我面临着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添加到一个间隔中,并且应该完成这个技巧。我正在尝试使用func.adddate,但是它会溢出,我猜想应该间隔为1970-1-1 +您输入的时间间隔。
我终于找到了一个可行的解决方案,多亏了https://stackoverflow.com/a/17236032/956541
因此,这条线变成:
( ((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))
谢谢你的帮忙,
恩里科
发布于 2014-10-02 09:30:01
解决方案是func.timestamp(日期)
((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)))https://stackoverflow.com/questions/24558252
复制相似问题