我有一个带有API的django应用程序。我创建了许多类似的查询:
class ShellMessageFilter(django_filters.FilterSet):
created = django_filters.DateTimeFilter(name="created",lookup_type="gte")
class Meta:
model = Server
fields = ['created']
class ServersDateList(ListAPIView):
serializer_class = ServerSerializer
queryset = Server.objects.all()
filter_class = ShellMessageFilter
从URL获取日期戳并过滤它。 但是现在我需要创建新的过滤器,显示最近两小时更新的服务器模型。 我怎么能这样做?
我会尝试这样的事情,但过滤器会被破坏并显示所有项目:
class ShellMessageFilter2Hour(django_filters.FilterSet):
import datetime
# lastTwoHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
# last_update = django_filters.DateTimeFilter(name=str(lastTwoHourDateTime.strftime('%Y-%m-%d %H:%M')),lookup_type="gte")
# last_update2 = datetime.datetime.now() - datetime.timedelta(minutes = 10)
# last_update = last_update2.strftime('%Y-%m-%d+%H:%M')
last_update = django_filters.DateTimeFilter("2016-04-23T15:31:50")
created = django_filters.DateTimeFilter(name="last_update",lookup_type="gte")
class Meta:
model = Server
fields = ['last_update']
class ServersDate2HourList(ListAPIView):
serializer_class = ServerSerializer
queryset = Server.objects.all()
filter_class = ShellMessageFilter2Hour
请帮忙,我的错误在哪里?
答案 0 :(得分:0)
在这种情况下,MethodFilter是您的朋友,并且您可以为视图使用一个过滤器类。
你可以这样实现:
class ShellMessageFilter(django_filters.FilterSet):
def updates_in_last_two_hours(self, value):
# You can toggle the value between True and False
if value == 'true':
right_now = datetime.datetime.now()
last_two_hours = right_now - datetime.timedelta(hours=2)
return self.filter(created__gte=last_two_hours)
else:
return self.filter()
created = django_filters.DateTimeFilter(name="created",lookup_type="gte")
updated_last_two_hours = django_filters.MethodFilter(
action=updates_in_last_two_hours)
class Meta:
model = Server
fields = ['created', 'updated_last_two_hours']
然后你可以在视图中使用updated_last_two_hours吗?updated_last_two_hours = true