Sneha Shinde
Sneha Shinde

Reputation: 353

django filter - how to get filtered objects

I have a model named Container which has the fields received and name. I'm using django-filter to filter on those fields. After filtering I get the result:

<list.filters.AdvancedSearchListFilter object at 0x7f68cd698828>

Here is my filter class:

class AdvancedSearchListFilter(django_filters.FilterSet):

    field-1 = django_filters.DateFromToRangeFilter(label='Received Date Range')

    class Meta:
        model = Container
        fields = ['field-1', 'field-2']

How do I get the filtered results?

Upvotes: 5

Views: 6213

Answers (2)

Forge
Forge

Reputation: 6834

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 = Container.objects.all().


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

{% for obj in filter %}
    {{ obj.field-2 }} - ${{ obj.field-1 }}<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:
    field-1 = django_filters.CharFilter(lookup_type='icontains')
    To get all entries with foo in field-1, set query to {'field-1': 'foo'}

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

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

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

Upvotes: 1

AKS
AKS

Reputation: 19831

Looking at the documentation you can access the queryset using f.qs where f is your filter object.

If you want to access the filtered objects in your views, for example if you want to paginate them, you can do that. They are in f.qs.

So if you are getting the results from the filter as following:

result = AdvancedSearchListFilter(query, queryset=queryset)

Note, that this query needs to be a dict and not a string:

# 2016-03-02
query = {'received': datetime.date(2016, 3, 2)} # or your own custom date

You can access the Container objects from the result using qs property:

container_objs = result.qs

I also looked at the implementation of DjangoFilterBackend in django-rest-framework and there also they use qs to access the objects:

    if filter_class:
        return filter_class(request.query_params, queryset=queryset).qs

Upvotes: 3

Related Questions