带有datetime的Django原始sql
我在django项目中使用postgres,在对db的复杂查询中使用connection.cursor()。今天,我在筛选器中使用datetime进行原始sql查询时遇到问题:带有datetime的Django原始sql,sql,django,postgresql,Sql,Django,Postgresql,我在django项目中使用postgres,在对db的复杂查询中使用connection.cursor()。今天,我在筛选器中使用datetime进行原始sql查询时遇到问题: with connection.cursor() as cursor: cursor.execute( "SELECT * from orders_orderstatus WHERE datetime > '2017-09-05 16:07:16'"
with connection.cursor() as cursor:
cursor.execute(
"SELECT * from orders_orderstatus WHERE datetime > '2017-09-05 16:07:16'"
)
row = [item[0] for item in cursor.fetchall()]
return row
因此,我们的列表是空的。但如果我从psql控制台查询这个,我会看到结果不是空的:
SELECT * FROM orders_orderstatus WHERE datetime > '2017-09-05 16:07:16';
id | status | datetime
----+--------------------+-------------------------------+
256 | created | 2017-09-05 16:10:59.602091+07
257 | delivered | 2017-09-05 16:11:00.834547+07
258 | created | 2017-09-05 16:11:03.499364+07
为什么django没有收到这个结果 这将展示python和psql如何解释datetime的字符串tzinfo psql使用字符串时间作为UTC。 python将其发送到数据库,并带有您所在时区的+hours\u 如果您的tz+07如此,请尝试使用python:
with connection.cursor() as cursor:
cursor.execute(
"SELECT * from orders_orderstatus WHERE datetime > '2017-09-05 09:07:16'"
)
row = [item[0] for item in cursor.fetchall()]
return row
以后尝试将datetime对象与tz一起使用
看起来您有以下设置:
USE_TZ=True
绕过Django的ORM可能很棘手。在许多情况下,最好坚持构建
QuerySet
s;使用这种方法可以很容易地执行上面显示的查询。这是。您是否在手动查询中使用事务处理?如果没有更多的信息,很难知道这里是否发生了这种情况。