一、查询当天的记录:

select * from `order` where TO_DAYS(create_time) = TO_DAYS(NOW())

注意: 这里的create_time是数据库中存储时间的字段名,会根据这个时间去和今天的时间对比获取数据。这里的 order表名 加上 `` (反引号 :就是键盘数字1左边的那个键(英文状态下))是因为 在mysql 中 order是一个关键字

二、查询7天前的数据

select * from `order`  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(create_time)

注意: 这里的create_time是数据库中存储时间的字段名,会根据这个时间去和今天的时间对比获取数据。这里的 order表名 加上 `` (反引号 :就是键盘数字1左边的那个键(英文状态下))是因为 在mysql 中 order是一个关键字

三、查询30天前的数据

查询30天前的数据 和查询7天前的数据是一样的

select * from `order`  where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(create_time)

在 python 使用 sql 原生命令

#导入原生sql模块
from django.db import connection

#对结果集进行美化
def dictfetchall(cursor):
    #获取游标描述
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc ],row))
        for row in cursor.fetchall()
        ]

#建立游标对象
cursor = connection.cursor()
#执行sql语句
cursor.execute("SELECT * FROM `order`  where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(create_time)")
#获取结果
# result = cursor.fetchall()
result = dictfetchall(cursor)
#返回结果
return HttpResponse(json.dumps(result,ensure_ascii=False,indent=4,default=str),content_type='application/json')

这就ok啦

Logo

更多推荐