在DRF中按时间过滤

huangapple go评论77阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年3月9日 22:52:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定