英文:
Filter by time in DRF
问题
在我的API中,有一个截止日期字段(ad end time),在模型中,这是一个简单的日期时间字段:
end_date = DateTimeField(null=True, blank=True)
在我的视图中,有多种广告筛选类型,但我需要一些复选框,用于比较当前日期和时间与该字段中写入的日期时间,基于此,只显示相关的广告。在DRF中是否有类似的功能(DjangoFilterBackend):
class AdAPI(generics.ListAPIView):
queryset = Ad.objects.all()
serializer_class = AdSerializers
filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
filterset_class = AdFilterSet
对于此功能,我将不胜感激。
英文:
I have an api with an end day field (ad end time), in the model, this is a simple datetime field:
end_date = DateTimeField(null=True, blank=True)
in my view there are several types of filtering for ads, but I need some checkbox that will compare the current date and time with the one written in this field, based on which only relevant ads will be displayed
Is there something similar in the DRF, like this(DjangoFilterBackend):
class AdAPI(generics.ListAPIView):
queryset = Ad.objects.all()
serializer_class = AdSerializers
filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
filterset_class = AdFilterSet
I will be grateful for the hint
答案1
得分: 1
你可以在过滤查询中使用 __lt
、__lte
、__gt
和 __gte
后缀来获取满足这些参数的对象集合。
参见这里:Django查询集字段查找
例如:
now = datetime.datetime.now()
ads_later_than_now = Ad.objects.filter(end_date__gt=now)
英文:
You can use __lt
, __lte
, __gt
, and __gte
suffixes in a filter query to obtain the set of objects that fulfill those parameters.
See here: Django queryset field lookups
For example:
now = datetime.datetime.now()
ads_later_than_now = Ad.objects.filter(end_date__gt=now)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论