Sneha Shinde Sneha Shinde - 1 month ago 13
Python Question

django filter - how to get filtered objects

I have a model named

which has the fields
. I'm using
to filter on those fields.
After filtering I get the result:

<list.filters.AdvancedSearchListFilter object at 0x7f68cd698828>

Here is my

class AdvancedSearchListFilter(django_filters.FilterSet):

received = django_filters.DateFromToRangeFilter(label='Received Date Range')

class Meta:
model = Container
fields = ['received', 'name']

How do I get the filtered results?


You should create an object of your filter class like this:

filter = FilterClass(query)

Where query is type dict, for example - to get all files named file.txt, set query to {'name': 'file.txt'}.
You can also specify the queryset argument, but if it's not provided then all the items in the default manager of the model will be used, in your case queryset = File.objects.all().

To get the filtered results, access filter.qs or iterate over filter:

{% for obj in filter %}
    {{ }} - ${{ obj.received }}<br />
{% endfor %}

Also, you didn't specify a lookup_type, by default it is the exact term. Add lookup_type to your filter class like this:

  • To search on part of the text:
    name = django_filters.CharFilter(lookup_type='icontains')
    To get all files with foo in name, set query to {'name': 'foo'}

  • To search on dates earlier than:
    received = django_filters.DateFilter(lookup_type='lt')
    To get all files received before today, set query to {'received':}

In case you would like to search on a date in range:
received = django_filters.DateFromToRangeFilter()
To get all files received in a date range, set query to {'received_0': start_date, 'received_1': end_date}

There are more examples in the formal documentation django-filter.