django之如何按日期查询数据
django按日期查询数据
1、数据库模型 。
from django.db import models class Get_time(models.Model): '''测试''' name = models.CharField(max_length=12) time= models.DateTimeField(auto_now_add=True)
2、序列化和分页。
from rest_framework import serializers from knife_manage import models class Get_time_Serializer(serializers.ModelSerializer): '''序列化''' class Meta: model = models.Get_time fields = '__all__' class PageNumber(PageNumberPagination): '''分页''' page_size = 50 page_size_query_param = 'size' max_page_size = 5 page_query_param = 'page'
3、路由。
url(r'^/test/$', views.Timeview.as_view({'get':'filter','post':'post'})),
4、视图。
class Timeview(ModelViewSet): authentication_classes = [] # 取消用户认证 queryset = models.Get_time.objects.all() serializer_class = Get_time_Serializer # 序列化数据 pagination_class = PageNumber() # 分 def filter(self, request, *args, **kwargs): """多条件查询匹配""" queryset = models.Get_time.objects.filter(time__year = 2020) # 按年查询 queryset = models.Get_time.objects.filter(time__month = 12) # 按月查询 queryset = models.Get_time.objects.filter(time__day= 9) # 按日查询 now = datetime.datetime.now() start = now-datetime.timedelta(hours=12, minutes=0, seconds=0) queryset = models.Get_time.objects.filter(time__gt= start) # 大于某个日期 queryset = models.Get_time.objects.filter(time__lt= start) # 小于某个日期 start_date = datetime.date(2009, 1, 1) end_date = datetime.date(2020, 3, 31) queryset = models.Get_time.objects.filter(time__range=(start_date, end_date)) # 按区间查询 queryset = models.Get_time.objects.filter(time__week_day=4) # 按星期几查询 pager_size = self.pagination_class.paginate_queryset(queryset=queryset, request=request, view=self) ser = self.serializer_class(instance=pager_size, many=True) return self.pagination_class.get_paginated_response(ser.data) def post(self, request, *args, **kwargs): """新增""" try: import random name=random.randint(10000,99999) return Response({'info': '操作成功!', 'code': 200}) except Exception: return Response({'info': '操作失败!', 'code': 400})
5、结果:
6、extra。
1)、用户选择日历查询。
range=['2019-03-04', '2019-06-24'] # 前台传过来的数据 start=[int(x) for x in range[0].split('-')] end=[int(x) for x in range[1].split('-')] start_date = datetime.date(start[0], start[1],start[2]) end_date = datetime.date(end[0],end[1],end[2])
2)、用户选择特定日期。
未设置时区时的操作
request_time='2012-09-09' time_split=[int(x) for x in request_time.split('-')] times='%s-%s-%s'%(time_split[0],time_split[1],time_split[2]+1) cday = datetime.strptime(times, '%Y-%m-%d') models.Get_time.objects.create(name=name,time=cday)
设置时区时的操作
配置文件设置时区:
TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_TZ = False
视图:
request_time='2012-09-09' cday = datetime.strptime(request_time, '%Y-%m-%d') models.Get_time.objects.create(name=name,time=cday)
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_time为datetime类型数据
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:16 比 2018-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;
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
python添加列表元素append(),extend()及 insert()
这篇文章主要介绍了python添加列表元素append(),extend()及 insert(),列表是储存元素的数据类型,既然能存储元素,那么就类似数据库一样,增删改查的一些功能就不能少了。下面我们就来先看看添加列表元素方法有哪些,需要的朋友可以参考一下2022-03-03
最新评论