Django: Generating a queryset from a GET request

django, django-queryset, django-views

Solution

You could do it with a list comp and and "interested params" set:

def search_items(request):
    if 'search_name' in request.GET:
        interested_params = ('color', 'shape')
        query_attrs = dict([(param, val) for param, val in request.GET.iteritems() 
                            if param in interested_params and val])

        items = Items.objects.filter(**query_attrs)

Just for fun (aka don't actually do this) you could do it in one line:

def search_items(request):
    items = Items.objects.filter(
        **dict([(param, val) for param, val in request.GET.iteritems() 
                if param in ('color', 'shape') and val])
    ) if 'search_name' in request.GET else None 

Problem

I have a Django form setup using GET method. Each value corresponds to attributes of a Django model. What would be the most elegant way to generate the query? Currently this is what I do in the view: ``` def search_items(request): if 'search_name' in request.GET: query_attributes = {} query_attributes['color'] = request.GET.get('color', '') if not query_attributes['color']: del query_attributes['color'] query_attributes['shape'] = request.GET.get('shape', '') if not query_attributes['shape']: del query_attributes['shape'] items = Items.objects.filter(**query_attributes) ``` But I'm pretty sure there's a better way to go about it.

Original source