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类型数据

id end_time value
1 2018-07-09 04:23:16 1
2 2018-07-015 04:23:16 3

使用上面的命令返回的结果为第一条,以下是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;

猜你喜欢

转载自blog.csdn.net/soga238/article/details/81049631