django - 过滤日期时间字段上的查询列表给出警告
问题描述
我在 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)。运行时警告)
我使用的格式与我在模型中使用的格式相同,那么为什么会显示警告?
解决方案
因为变量并不是“with ”的日期时间对象f
,所以它们只是字符串。t
tzinfo
这样的事情会消除警告,
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])
推荐阅读
- r - facet_grid 根据簇的颜色单元格
- python - 多次发送时sendto的问题(Python)
- api - foursquare api返回消费者禁用
- windows - Go - 不允许使用内部包 [...]
- python - 如何在python中进行指数非线性回归
- docker - Jupyter Datascience docker - 连接到 mssql 服务器
- swift - 如何在应用中搜索用户?(最具成本效益的方式)在 Firebase
- installation - 运行 preseed 时 Caldera Debian 安装停止
- c# - 在winform中获取flowlyaoutpanel的子用户控件
- excel - 从 VBA 运行时在 Excel 中添加 Ole 对象会引发错误