Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DJango filter_queryset

I am new to DJango and DRF and have been asked to manage some DJango/DRF related code. After a lot of search I am still unable to find a complete example on how filter_queryset works and how can it be used with different arguments.

At some places I see it used like the following,

self.filter_queryset(queryset)

and at other places it is used with some arguments. It would be helpful if some one can explain the fundamentals like how and when to use it, what are the dependent variables (lookup_field, filter_backends etc...) and arguments and how to set them up.

I have searched a lot and also gone through the docs. If i have missed any doc kindly let me know.

like image 443
Subbu Avatar asked Dec 19 '18 02:12

Subbu


1 Answers

The filter_queryset()--(source code) is a method which is originally implemented in GenericAPIView -- (DRF doc) class.

def filter_queryset(self, queryset):
    """
    Given a queryset, filter it with whichever filter backend is in use.
    You are unlikely to want to override this method, although you may need
    to call it either from a list view, or from a custom `get_object`
    method if you want to apply the configured filtering backend to the
    default queryset.
    """
    for backend in list(self.filter_backends):
        queryset = backend().filter_queryset(self.request, queryset, self)
    return queryset

I think the functionality of the method is clearly visible from the doc strings.


".....and at other places it is used with some arguments"

The views's filter_queryset() method takes only one parameter, which is the queryset to be filtered.

But, filter-backends' filter_queryset() method takes three arguments which are request,queryset and the view itself.


What are FilterBackends?
Filterbackends are classes which helps us to filter the queryset with complex lookups and some other stuff.

DRF has few built-in backends which can be found here.DRF official docs recommend to use django-filter package for advanced filtering purposes.

How filter-backend working?
Take a look at the source code of DjangoFilterBackend class and it's methods...It's filter_queryset(...) method plays key role in the filtering process.
I would recommend to go through the doc of django-filter to understand the usage of the same with more examples.

By defining filterset_class, you could've more controll over the filtering process (such as providing lookup_expr etc)

like image 117
JPG Avatar answered Nov 06 '22 14:11

JPG