Django orm实现时间查询

一:关于orm的解释

ORM:Object Relational Mapping(关系对象映射)

        类名==>对应==>数据库中的表名

        类属性==>对应==>数据库里的字段

        类实例==>对应==>数据库表里的一行数据

        obj.id  obj.name==>对应==>类实例对象的属性

二:python以及django-orm中关于时间段的一些查询方法

(一)python控制台示例(datetime.datetime类型 转换为 字符串类型 %Y-%m-%d):


>>> import datetime
>>> now = datetime.datetime.now()
>>> print(now)
>>> 2022-12-06 17:32:20.263300
>>> print(str(now).split(' ')[0])
>>> 2022-12-06

(二)python代码实例(时间格式为字符串类型%Y-%m-%d):

import datetime

'''起始时间'''
start = '2022-12-06'
start_year = start.split('-')[0]
start_mouth = start.split('-')[1]
start_day = start.split('-')[2]
start_time = datetime.date(int(start_year),int(start_mouth),int(start_day))

'''终止时间'''
end = '2022-12-08'
end_year = end.split('-')[0]
end_mouth = end.split('-')[1]
end_day = end.split('-')[2]
end_time = datetime.date(int(end_year),int(end_mouth),int(end_day))

## start 和 end 这里只是例子,可以根据自己实际情况定义,例如从前端拿到的要查询的时间,起止时间,时间段等等

1、lt:小于2022-12-06
query_filter_list = your_model_name.objects.filter(your_datetime_column__lt=start_time)

2、lte:小于等于2022-12-06
query_filter_list = your_model_name..objects.filter(your_datetime_column___lte=start)

3、gt:大于2022-12-06
query_filter_list = your_model_name.objects.filter(your_datetime_column___gt=start)

4、gte:大于等于2022-12-06
query_filter_list = yourobject.objects.filter(your_datetime_column__gte=start)

5、range:查询时间段2022-12-06至2022-12-08
query_filter_list = your_model_name.objects.filter(your_datetime_column__range=(start_time, end_time))

6、year:查询2022年
query_filter_list = your_model_name.objects.filter(your_datetime_column__year=int(end_year))

7、month:查询12月
query_filter_list = your_model_name.objects.filter(your_datetime_column__month=int(end_mouth ))

8、day:查询8号当天
query_filter_list = your_model_name.objects.filter(your_datetime_column__day=int(end_day))

9、week_day:星期2
query_filter_list = your_model_name.objects.filter(your_datetime_column__week_day=2)

10、获取今天,昨天,明天的日期,日期格式为yyyy-MM-dd
from django.utils.timezone import now, timedelta

date_time = now().date() + timedelta(days=-1)    #昨天
date_time = now().date() + timedelta(days=0)     #今天
date_time = now().date() + timedelta(days=1)     #明天

11、获取前一个月,后一个月
import dateutil.relativedelta
import datetime
now = datetime.datetime.now()


forward_mouth_date = now + dateutil.relativedelta.relativedelta(months=-1)  ## 当前时间前一个月
back_mouth_date = now + dateutil.relativedelta.relativedelta(months=1)      ## 当前时间后一个月

你可能感兴趣的:(python,django,python,后端)