Django Rest Framework按日期范围过滤

时间:2019-11-13 13:12:29

标签: django django-models django-rest-framework django-views

我给了View类

class eventList(ListAPIView):

       queryset = Event.objects.all().filter(is_active=1, is_approved=1)
       serializer_class = eventSerialiser
       filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
       search_fields = ['event_name', 'event_address', 'start_date', 'start_time', 'end_time', 
                         'age_max', 'age_min','event_organizer__name', 'event_type__name', 
                         'event_city__name', 'event_tag__name']
       filterset_fields = ['event_name', 'start_date', 'start_time', 'end_date', 'end_time', 
                           'age_max', 'age_min', 'event_organizer', 'event_type', 'event_city', 
                           'event_tag']
       ordering_fields = '__all__'
       ordering = ['-id']

所有过滤器都可以正常工作,但是如何根据日期获取数据范围为start_dateend_date

3 个答案:

答案 0 :(得分:5)

终于有了很长一段时间的解决方案

  • 双下划线 gte 大于等于
  • 双下划线 gt 用于大于
  • 双下划线 lte 小于等于
  • 双下划线 lt 小于

    Counter({1: 10500, 2: 400, 3:10})

答案 1 :(得分:1)

https://django-filter.readthedocs.io/en/latest/ref/filters.html#daterangefilter

class Comment(models.Model):
    date = models.DateField()

class F(FilterSet):
    date = DateFromToRangeFilter()

    class Meta:
        model = Comment
        fields = ['date']

# Range: Comments added between 2016-01-01 and 2016-02-01
f = F({'date_after': '2016-01-01', 'date_before': '2016-02-01'})

# Min-Only: Comments added after 2016-01-01
f = F({'date_after': '2016-01-01'})

# Max-Only: Comments added before 2016-02-01
f = F({'date_before': '2016-02-01'})

答案 2 :(得分:0)

我正在使用过滤器-DateFromToRangeFilter。 https://django-filter.readthedocs.io/en/master/ref/filters.html#datefromtorangefilter

class BookFilter(filters.FilterSet):
    min_price = filters.NumberFilter(field_name="price", lookup_expr="gte")
    max_price = filters.NumberFilter(field_name="price", lookup_expr="lte")
    start_date = filters.DateFilter(lookup_expr="gte")
    end_date = filters.DateFilter(lookup_expr="lte")

    class Meta:
        model = Book
        fields = [
            "authors",
            "publishing_house",
            "is_bestseller",
            "category",
            "min_price",
            "max_price",
            "start_date",
            "end_date",
        ]

from django_filters.rest_framework import DjangoFilterBackend

class BookListView(generics.ListAPIView):
    """List of all books"""

    serializer_class = catalog.serializers.BookCatalogSerializer
    pagination_class = ProductsPagination
    queryset = Book.objects.filter(is_active=True)
    filter_backends = [DjangoFilterBackend]
    filterset_class = BookFilter

结果SQL

WHERE ("catalog_book"."is_active" = true AND "catalog_product"."start_date" >= '2016-01-01T00:00:00+03:00'::timestamptz AND "catalog_product"."end_date" <= '2016-01-01T00:00:00+03:00'::timestamptz)