django 后台格式化数据库查询出的日期

在项目中,我遇到这样的情况,使用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)
原文地址:https://www.cnblogs.com/yasmi/p/5110447.html