- 根据 type()._ name_ 判断字段是不是日期类型,因为有的字段是DateField,所以用type(field_obj)._ name_ in 'DateTimeField' 可以适用其它日期类型
- 在日期字段后面加上 __gte 实现日期的过滤
使用datetime.now()会报下面的错误
DateTimeField BookSection.created received a naive datetime (2017-12-05 16:12:53.719613) while time zone support is active.
时区问题:
-
datetime.now()生成的不带时区的utc时间称为native time
-
使用django.utils.timezone.now()输出的是带时区的utc时间,称为active time
注意format的使用场景
由于filter_field 在中间有过修改(拼接__gte),所以select标签的name属性应该使用{filter_field},而不是 %s
datetime.now().date().replace()的用法
可以传参数 year,month,day...若replace(month=1,day=1),代表这个月月初距离今天的日期
下面代码作用是保留过滤框的值
- 千万注意 v 是日期类型,做if 判断时一定要转换成字符串类型
for k,v in date_dic.items():
selected = ''
if filter_conditions.get(filter_field_item) == str(v):
selected = 'selected'
select_ele += "<option value=%s %s>%s</option>"%(v, selected, k)
from django.utils.timezone import datetime, timedelta
@register.simple_tag
def render_filter_column(filter_field,admin_class,filter_conditions):
'''过滤数据'''
select_ele = "<select class='form-control' name='{filter_field}'><option value=''>---</option>"
field_obj = admin_class.model._meta.get_field(filter_field)
if type(field_obj).__name__ in 'DateTimeField':
filter_field_item = "%s__gte" % filter_field
date_dic = {}
today_ele = datetime.now().date()
date_dic['今天'] = today_ele
date_dic['近七天'] = today_ele - timedelta(days=7)
date_dic['本月'] = today_ele.replace(day=1)
date_dic['近一月'] = today_ele - timedelta(days=30)
date_dic['近90天'] = today_ele - timedelta(days=90)
date_dic['近180天'] = today_ele - timedelta(days=180)
date_dic['今年'] = today_ele.replace(month=1, day=1)
date_dic['近一年'] = today_ele - timedelta(days=365)
for k,v in date_dic.items():
selected = ''
if filter_conditions.get(filter_field_item) == str(v):
selected = 'selected'
select_ele += "<option value=%s %s>%s</option>"%(v, selected, k)
else:
filter_field_item = filter_field
select_ele += "</select>"
select_ele = select_ele.format(filter_field=filter_field_item)
return mark_safe(select_ele)
网友评论