5

I am new to DRF. I went through the example of filtering queryset at http://www.django-rest-framework.org/api-guide/filtering/#filtering-and-object-lookups

This link contains description about queryset filtering, as well as DjangoFilterBackend. As far as I am able to understand, they are serving the same purpose. But it's not clear when to use any one of them. In some of the cases, both queryset and filter_backends are used :-

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('username', 'email')

Can anyone let me know, what's the difference between these two ?which one of these two have to be used, in which situations, we must prefer one over another ?

Thanks in advance

Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
  • queryset filtering is the actual operation, and DjangoFilterBackend is what carries it out from inside a view – arjunattam Oct 16 '17 at 12:57

1 Answers1

4

DjangoFilterBackend provides ready to use implementation for filtering. Think of it same as api_view vs generic ListApiView. Filtering backend allow you to achieve various filtering (search, ordering etc.) with writing just a line of code (that is enabling the filter backend). You could achieve the same result by not using any filter backend and instead filtering yourself using the query parameter.

Later could look something like this:

for q_key in request.query_params.keys():
        if q_key == 'from_ts':
            from_timestamp = int(request.query_params[q_key])
        elif q_key == 'to_ts':
            to_timestamp = int(request.query_params[q_key])
        elif q_key == 'location':
            location_id = (request.query_params[q_key])
        elif q_key == 'from_rating':
            rating_low = int(request.query_params[q_key])
        elif q_key == 'to_rating':
            rating_high = int(request.query_params[q_key])

And filter using these parameters:

snippets = ParResponse.objects.filter(
        device__location__id=location_id,
        owner_user=request.user,
        timestamp__gte=end_date,
        timestamp__lte=from_date,
        overall_rating__lte=rating_high,
        overall_rating__gte=rating_low,
        ).order_by('-timestamp')
mahoriR
  • 4,377
  • 3
  • 18
  • 27