首页 > 解决方案 > 过滤日期时间字段上的查询列表给出警告

问题描述

我在 Django 中从我的 ORM 中查询一个模型,如下所示:

client = Client.objects.get(pk=cname).user
items = Allotment.objects.filter(sales_order__owner=client).order_by('-id')

并想按我从 URL 中作为参数获取的日期时间过滤它

URL:  GET /allotment-reports/?cname=3&to=2020-07-30+15:07&from=2020-07-01+15:07 

所以我尝试了这个:

f = request.GET['from']
t = request.GET['to']

items = items.filter(dispatch_date__range = [f,t])

但不断收到警告:

RuntimeWarning:DateTimeField Allotment.dispatch_date 在时区支持处于活动状态时收到了一个简单的日期时间(2020-07-30 15:07:00)。运行时警告)

我使用的格式与我在模型中使用的格式相同,那么为什么会显示警告?

标签: djangodjango-rest-framework

解决方案


因为变量并不是“with ”的日期时间对象f,所以它们只是字符串ttzinfo

这样的事情会消除警告,

import pytz
from datetime import datetime

dt_format = '%Y-%m-%dT%H:%M:'  # or suitable format
f = datetime.strptime(request.GET['from'], dt_format).replace(tzinfo=pytz.UTC)
t = datetime.strptime(request.GET['to'], dt_format).replace(tzinfo=pytz.UTC)

items = items.filter(dispatch_date__range=[f, t])

推荐阅读