Django ORM查询指定日期范围内的数据

######Django ORM查找指定日期范围内的方法

 dt_s= datetime.now().date()  # 2018-7-15
 dt_e = (dt_s- timedelta(7))  # 2018-7-08
 objs = Record.objects.filter(end_time__range=[dt_s, dt_e])
 objs = Record.objects.filter(Q(end_time__=dt_s) & Q(end_time__lt=dt_e)) # 效果相同

end_timedatetime类型数据

idend_timevalue
12018-07-09 04:23:161
22018-07-015 04:23:163

使用上面的命令返回的结果为第一条,以下是ORM封装的SQL语句,因为2018-07-15 04:23:162018-07-15

select * from record where end_time between 2018-07-08 and 2018-07-15;

You can use range anywhere you can use BETWEEN in SQL — for dates, numbers and even characters.
Warning
Filtering a DateTimeField with dates won’t include items on the last day, because the bounds are interpreted as “0am on >the given date”. If pub_date was a DateTimeField, the above expression would be turned into this SQL:
SELECT … WHERE pub_date BETWEEN ‘2005-01-01 00:00:00’ and ‘2005-03-31 00:00:00’;
Generally speaking, you can’t mix dates and datetimes.

要将end_time转换为日期,就能返回两条数据了

select * from record where date(end_time) between 2018-07-08 and 2018-07-15;
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值