【发布时间】:2021-01-27 17:16:48
【问题描述】:
我只是想过滤两个日期之间的记录。
假设有一个记录表Measurements 具有属性timestamp:
class Measurements(models.Model):
id = models.BigAutoField(primary_key=True)
timestamp = models.DateTimeField()
当我检查最后一条记录Measurements.objects.last().timestamp 的timestamp 时,它返回:
datetime.datetime(2020, 10, 13, 6, 29, 48, 90138, tzinfo=<UTC>)
现在我想过滤日期 from_date 和 to_date 之间的数据。根据之前关于这个问题的问题,我使用了make_aware。为了测试,我使用count 来获取条目数量。
from .models import *
from datetime import datetime
from django.utils.timezone import make_aware
def get_measurements(request):
from_date = make_aware(datetime(2020, 10, 12, 15, 30, 0, 0))
to_date = make_aware(datetime(2020, 10, 12, 16, 0, 0, 0))
print(from_date)
print(to_date)
measurements = DriveMeasurements.objects.filter(
plc_timestamp__range=["2020-01-01", "2020-01-31"])
print(measurements.count())
在我的 shell 中打印两个日期时,它会返回:
datetime.datetime(2020, 10, 12, 15, 30, tzinfo=<UTC>)
datetime.datetime(2020, 10, 12, 16, 0, tzinfo=<UTC>)
当我运行上面的函数时,Django 会触发以下消息:
RuntimeWarning:在时区支持处于活动状态时,DateTimeField Measurements.timestamp 收到了一个幼稚的日期时间 (2020-01-31 00:00:00)。 warnings.warn("DateTimeField %s 收到了一个简单的日期时间 (%s)"
打印语句print(measurements.count()) 打印0,但数据库中有~18000 条记录。
那么为什么过滤器不起作用并抛出 Django 消息?
【问题讨论】:
标签: python django datetime django-orm