Search code examples
pythondjangodjango-filter

django-filter get queryset


I am using django-filter v1.1.0 , django 1.11. I want a dynamic filter for a model. I have created filters.py which contains the respective config for model filters. This site tells that:

It will generate a Django Form with the search fields as well as return the filtered QuerySet.

It here refers to SomeModelFilter function. I tried applying len and objects functions to it's object, but it returns

AttributeError: 'SomeModelFilter' object has no attribute 'len'
AttributeError: 'SomeModelFilter' object has no attribute 'objects'

I want to get the filtered content. It doesn't seem to be a QuerySet to me.

filters.py

from project_app.models import *
import django_filters


class SomeModelFilter(django_filters.FilterSet):
    class Meta:
        model = SomeModel
        fields = ['field_a', 'field_b', 'field_c', 'field_d']

views.py

    somemodel_list = SomeModel.objects.all()
    somemodel_filter = SomeModelFilter(request.GET, queryset=somemodel_list)

    print(len(somemodel_filter)) # This gives the first error
    print(somemodel_filter.objects.all()) # This gives the second error

I want to get the filtered content, hopefully which is contained in somemodel_filter object.


Solution

  • The problem is in this line print(somemodel_filter.objects.all()). somemodel_filter is not model, it's filterset instance and since it's don't have objects attribute. To get filtered queryset use qs attribute, like this:

    print(somemodel_filter.qs)
    

    You can find example of filter usage here.