我有一些模型時間戳字段:Django - 如何使用Django Rest Framework按日期過濾?
models.py
class Event(models.Model):
event_type = models.CharField(
max_length=100,
choices=EVENT_TYPE_CHOICES,
verbose_name=_("Event Type")
)
event_model = models.CharField(
max_length=100,
choices=EVENT_MODEL_CHOICES,
verbose_name=_("Event Model")
)
timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Timestamp"))
然後我使用Django的REST的框架來創建一個API端點這個類,Django的過濾器提供過濾功能如下:
from .models import Event
from .serializers import EventSerializer
from rest_framework import viewsets, filters
from rest_framework import renderers
from rest_framework_csv import renderers as csv_renderers
class EventsView(viewsets.ReadOnlyModelViewSet):
"""
A read only view that returns all audit events in JSON or CSV.
"""
queryset = Event.objects.all()
renderer_classes = (csv_renderers.CSVRenderer, renderers.JSONRenderer)
serializer_class = EventSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('event_type', 'event_model', 'timestamp')
使用以下設置:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
}
我可以通過event_type
和event_model
進行篩選,但是在篩選時間戳字段時遇到問題。從本質上講,我要讓這相當於以下API調用:
AuditEvent.objects.filter(timestamp__gte='2016-01-02 00:00+0000')
我期望我可以做如下:
response = self.client.get("/api/v1/events/?timestamp=2016-01-02 00:00+0000", **{'HTTP_ACCEPT': 'application/json'})
雖然這incorect。我如何進行API調用,返回時間戳大於或等於某個值的所有對象?
嗯,我我仍然得到0響應,當我應該得到1.我試過使用'django_filters.DateTimeFilter'和'django_filters.IsoDateTimeFilter'。任何想法,爲什麼這可能是這種情況? – orange1