在項目中,我遇到這樣的情況,使用ajax獲取查詢出來的數據,而這些數據中某個字段是日期datetime格式,在模板中顯示的樣式很怪異。由於前端使用了js控件,也不能使用django的模板過濾器。
所以這種情況下,我想將日期從數據庫中查詢出來就使用固定好的格式。
django 中直接執行sql語句查詢
from django.db import connection,transaction from django.core.paginator import Paginator #查詢記錄 sql_sentence='select * from log where datefrom>=%s and dateto<=%s' params=['2015-01-01','2015-02-01'] cursor = connection.cursor() records=cursor.execute(sql_sentence,params) #分頁 pages=Paginator(records,page_size) records=pages.page(page_num).object_list
django 使用sql語句,加上params參數,會進行在參數加上引號進行轉換,這是防止攻擊的一種措施,雖然我們也可以直接通過字符串拼接方式,但是顯示不如前種安全。
sql_sentence='select xxx,xxx,date_format(log_at,"%Y-%m-%d %H:%i:%S") as log_at from log where datefrom>=%s and dateto<=%s'
但是將sql_sentence換成上面的寫法后,django將時間格式"%Y-%m-%d %H:%i:%S" 中的%s誤認為是一個參數了。
研究后,使用該方法可以良好解決。
date_format="%Y-%m-%d %H:%i:%S" select xxx,xxx,date_format(log_at,%s") as log_at from log where datefrom>=%s and dateto<=%s #將格式變為一個參數 params.append(date_format) params.extend(['2015-01-01','2015-02-01']) #查詢數據庫 cursor = connection.cursor() records=cursor.execute(sql_sentence,params)