user3601503 user3601503 - 5 months ago 24
Python Question

How to set a Django filter to select all

I have a view in Django that will read a get request and its parameters and make a query based on the parameters. Currently my view looks like this:

def getInventory(request):
c = request.GET.get('category', '')
g = request.GET.get('gender', '')
s = request.GET.get('size', '')

available = Item.objects.filter(gender=g,category=c,size=s)
data = serializers.serialize('json',available)
return HttpResponse(data,'json')


Sometimes, though, one of the parameters is not specified. I would like this to result in a value representing 'all' rather than an individual value. Is this possible in the way I've done it? I've tried
gender=None
but that just results in an empty list.

Answer

You need to apply a filter only if you want to filter something. You could do something like this:

# Start off with a base queryset
available = Item.objects.all()

allowed_filters = ['category', 'gender', 'size']
for f in allowed_filters:
    if request.GET.get(f):
        available = available.filter(**{f: request.GET[f]})

data = serializers.serialize('json',available)
return HttpResponse(data,'json')

That said, you might want to consider using the Forms API to validate the inputs before passing them to your queryset.