/Users/huatai/onesre_venv3/lib/python3.9/site-packages/django/db/models/fields/__init__.py:1367: RuntimeWarning: DateTimeField Test.count_time received a naive datetime (2021-02-21 03:50:13.414188) while time zone support is active.
warnings.warn("DateTimeField %s received a naive datetime (%s)"
System check identified no issues (0 silenced).
这显然很可能就是导致SQL时间错误的原因。
参考 Djgnso: Time zones 可以看到默认是关闭时区支持的。要激活时区支持,需要在设置文件中设置 USE_TZ = True 。但是,需要注意,如果使用 django-admin startproject 创建的 settings.py 就会默认包含 USE_TZ = True 。也就是说,我的开发项目默认是启用了时区支持。
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if timezone.is_aware(now):
now = timezone.localtime(now)
完整代码如下:
import datetime
from django.contrib import admin
from django.contrib.admin.filters import DateFieldListFilter
from django.utils.translation import gettext_lazy as _
class MyDateTimeFilter(DateFieldListFilter):
def __init__(self, *args, **kwargs):
super(MyDateTimeFilter, self).__init__(*args, **kwargs)
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if timezone.is_aware(now):
now = timezone.localtime(now)
today = now.date()
self.links += ((
(_('Next 7 days'), {
self.lookup_kwarg_since: str(today),
self.lookup_kwarg_until: str(today + datetime.timedelta(days=7)),
}),
))
class BookAdmin(admin.ModelAdmin):
list_filter = (
('published_at', MyDateTimeFilter),
)
from datetime import datetime, timedelta
from rest_framework import viewsets
from rest_framework.response import Response
class TestViewSet(viewsets.ModelViewSet):
serializer_class = TestSerializer
def list(self, request):
time_threshold = datetime.now() - timedelta(minutes = 1)
queryset = Test.objects.all().filter(count_time__gte = time_threshold).order_by('count_time')
return Response(serializer_class.data)
但是运行报错
...
AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.
basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.