/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时间错误的原因。
时区时间
当前时区的naive time其实是默认时间:
from datetime import datetime
naive_dt = datetime.now()
from django.utils import timezone
timezone.localtime(timezone.now())
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.
from datetime import datetime, timedelta
from rest_framework import viewsets
class TestViewSet(viewsets.ModelViewSet):
serializer_class = HygonWafMonitorSerializer
def get_queryset(self):
time_threshold = datetime.now() - timedelta(minutes = 1)
queryset = Test.objects.all().filter(count_time__gte = time_threshold).order_by('count_time')
return queryset
关闭分页
由于我们使用了1分钟过滤数据集,所以返回数据集很小,不需要分页,所以在视图中关闭分页
...
class TestViewSet(viewsets.ModelViewSet):
...
pagination_class = None