2017-09-05 91 views
0

我用的Postgres我的Django項目,併爲複雜的查詢到DB I使用connection.cursor()。今天我與日期時間原始SQL查詢的問題過濾器:Django的原始SQL與日期時間

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沒有收到這個結果?

+0

繞過Django的ORM可能會非常棘手。在許多情況下,最好堅持構建'QuerySet';上面顯示的查詢可以很容易地用這種方式執行。 – Chris

+0

無論如何,[與PostgreSQL的兩個連接可能會看到不同的數據](https://www.postgresql.org/docs/current/static/mvcc-intro.html)。這是[一個功能](https://en.wikipedia.org/wiki/Multiversion_concurrency_control)。您是否使用手動查詢進行交易?沒有更多的信息,很難知道這是否是這裏發生的事情。 – Chris

回答

1

這是展示你的Python和psql如何解釋日期時間的字符串tzinfo。

PSQL使用字符串時間UTC。 蟒蛇把它與+ hours_of_your_time_zone

到DB如果你的TZ +07所以在蟒蛇嘗試:

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