Skip to content Skip to sidebar Skip to footer

How Can Filter By List In Django

I am trying to filter a queryset by a list I am getting unicode data into format of 1,4,5,6 by category = request.GET.getlist(category') print type(category) data = Leads.objec

Solution 1:

I done some steps wrong.finally i got and found solution.

    category = request.GET.get('category')
l1=[]
    category_list =category.split(',')
    for i in category_list:
        a =int(i)
        l1.append(a)

cust_leads = CustomerLeads.objects.filter(item_required__id__in= l1 )

Solution 2:

You can also use the QueryDict.getlist to resolve query parameter lists for your request:

from django.http.request import QueryDict

query = QueryDict('category=1&category=2')
categories = query.getlist('category')  # -> ['1', '2']
leads = Leads.objects.filter(item_required__id__in=categories)

This way user can supply you a list of categories by adding them one-by-one into the query. This solution might be good enough for you.

However, your user (or you) might want to supply free style lists, and they might be multiple in your queries. In that case you would have to get all lists, which can be lists of primary keys, and map them to a flat list which can be used in a Django filter...

from itertools import chain
from django.http.request import QueryDict

query = QueryDict('categories=1,2,3&categories=4,5')
categories_strings = query.getlist('categories')  # -> ['1,2,3', '4,5']
categories = list(chain.from_iterable(
    map(lambda categories: categories.split(','), categories_strings))
)  # -> ['1', '2', '3', '4', '5']
leads = Leads.objects.filter(item_required__id__in=categories)

Luckily for us, you could easily write this into a neat little function:

# Your myapp/utils.py module
from itertools import chain

# Python 3.5+ type type annotated function, you can use# this without the type annotations in Python 2.7 as welldefget_query_list(querydict: QueryDict, key: str) -> list:return list(chain.from_iterable(
        map(lambdaquery: query.split(','), querydict.getlist(key)))
    )

And this is how it works:

from django.http.request import QueryDict
from myapp.utils import get_query_list

q = QueryDict('a=1&a=2&a=3,4')
get_query_list(q, 'a')  # -> ['1', '2', '3', '4']

You can use it from your view:

# Your myapp/views.py modulefrom myapp.utils import get_query_list

defmy_view(request):
    categories = get_query_list(request.GET, 'categories')  # or 'category'# ...

This is the more verbose way instead of using a singular query parameter in place of a list and supports multiple different formats.

Add type assortions as necessary:

defmy_view(request):
    # A nice and neat one-liner
    categories = get_query_list(request.GET, 'categories')  # or 'category'for item in categories:
        try:
            assertint(item)
        except ValueError:
            raise ValidationError('{} is not of correct type {}'.format(item, int))
    # Everything should be parsed and validated
    leads = Leads.objects.filter(item_required__id__in=categories)

This approach is often needed with Django when implementing search or generic filters.

Post a Comment for "How Can Filter By List In Django"