Home > Software engineering >  Django-filters query params conflict
Django-filters query params conflict

Time:06-01

I am trying to work with filtering db by query params from the link that looks like this:

{{url}}/api/books?author="XXX"&from=2003&to=2051&acquired=true

I already handled author and acquired params but am stuck with from and to. My filter.py looks like this:

class BookFilter(django_filters.FilterSet):
      author = django_filters.CharFilter(field_name="authors__fullname", lookup_expr="icontains")

      from = django_filters.NumberFilter(field_name="published_year", lookup_expr="gte")
      to = django_filters.NumberFilter(field_name="published_year", lookup_expr="lte")

      acquired = django_filters.BooleanFilter(field_name="acquired")

      class Meta:
          model = Book
          fields = [
                  "author",
                  "from",
                  "to",
                  "acquired"
                  ]

I am looking for a way to assign these query params without overwriting key words (from and to) which is obviously a terrible idea.

CodePudding user response:

You don't need to define special BookFilter class. This task can simply done on view level. Just define a DateFilter class to filter according to the dates, and the other type of filters like search by name or order by price can be implemented on view level. (Make sure your model have a created_at field). Here is an example

from django_filters import rest_framework as rest_filters

from apps.yourappname.models import YourModel

from django_filters import rest_framework as rest_filters


class DateFilter(rest_filters.FilterSet):   
  created_at = rest_filters.DateFromToRangeFilter()

  class Meta:
     model = YourModel
     fields = ['created_at']

class YourAPIView(ListAPIView):
  serializer_class = YourModelSerializer
  filter_backends = [filters.SearchFilter, filters.OrderingFilter, 
                     rest_filters.DjangoFilterBackend, ]

  filter_class = DateFilter
  search_fields = ['authors__fullname' ]
  ordering_fields = [ 'created_at', ]

  def get_queryset(self):
     dataset_queryset = 
     YourModel.objects.filter(id=self.request.user.id)
     return dataset_queryset

When you filter by date, your URL will look like this: http://127.0.0.1:8000/api/yourappname/id/files/?created_at_after=2022-04-19&created_at_before=2022-05-28

CodePudding user response:

For anyone that may have same problem: I managed to create a workaround in which I create copy of querydict, pop() "from" and "to" values and assign them to newly created "from_date" and "to_date" keys.

  • Related