2016-08-19 50 views
2

我正在使用SQLObject,一个用于Python 2.7的包装器来管理SQL查询。我知道我可以通过使用词典,如选择数据:Python SQL对象按字典和日期选择数据

restrictions = { ... } 
selection = sql_table.selectBy(**restrictions).orderBy('-createdtime') 

我还可以通过执行查询日期:

selection = sql_table.select(sql_table.q.creatdtime>=datetime.datetime(year, month, day, 0, 0, 0, 0) 

不过,我想用两者一起用日期排序以及字典配对。当我试图把它们放在一起像这样:

selection = sql_table.select(**restrictions, sql_table.q.creatdtime>=datetime.datetime(year, month, day, 0, 0, 0, 0) 

它不起作用。有什么办法可以通过一系列日期时间和字典配对来过滤SQL查询吗?

回答

2

修复了这个问题。如果你在这里面临着同样的问题,这里是解决方案:

因为SQLObject的包装进入直SQL查询Python支持,我选择来构建它自己。首先,我解压所有的限制作为查询

select_string = " AND ".join(str(key) + "=" + str(restrictions[key]) for key in restrictions.keys()) 

然后,我想添加一个基于我的日期限制。我知道,存储日期和时间在我的数据库中的列被称为createdtime,所以我把字符串作为

select_string += " AND " + 'createdtime>=' + '"' + str(datetime.datetime(year, month, day, 0, 0, 0, 0)) + '"' 

注意引号的DateTime对象,尽管它已被强制转换为字符串,它还需要有引号工作。

因此,我最终的代码如下所示:

select_string = " AND ".join(str(key) + "=" + str(restrictions[key]) for key in restrictions.keys()) 
if date1: 
    select_string += " AND " + 'createdtime>=' + '"' + str(datetime.datetime(year, month, day, 0, 0, 0, 0)) + '"' 
if date2: 
    select_string += " AND " + 'createdtime<=' + '"' + str(datetime.datetime(year2, month2, day2, 0, 0, 0, 0)) + '"' 
selection = sql_table.select(select_string).orderBy('-createdtime') 
return selection