2

我正在使用 SQLObject,一个用于管理 SQL 查询的 Python 包装器,以及 Python 2.7。我知道我可以使用字典来选择数据,例如:

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 查询?

4

1 回答 1

2

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

由于 Python 的 SQLObject 包装器支持直接输入 SQL 查询,因此我选择自己构建它。首先,我将所有限制解压缩为查询

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
于 2016-08-25T17:31:33.157 回答