[Fixed]-Django Rest Framework filter by date range

27πŸ‘

βœ…

This work for me.

  • double underscore gte is for greater than equal to

  • double underscore gt is for greater than

  • double underscore lte is for less than equal to

  • double underscore lt is for less than

      filterset_fields = {
          'start_date':['gte', 'lte', 'exact', 'gt', 'lt'],
          'id':['exact'],
          'event_name':['exact'],
          'start_time':['exact'],
          'end_date':['exact'],
          'end_time':['exact'],
          'age_max':['gte', 'lte', 'exact', 'gt', 'lt'],
          'age_min':['gte', 'lte', 'exact', 'gt', 'lt'],
          'event_organizer__name':['exact'],
          'event_type__name':['exact'],
          'event_city__name':['exact'],'event_tag__name':['exact']
      }
    
πŸ‘€Sohail Ahmad

1πŸ‘

I am using filter – 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

Result 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)
πŸ‘€V. Chikunov

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'})
πŸ‘€Ic3 Sandy

Leave a comment