tags:

views:

35

answers:

2

How can I do this?

I only what to filter if the request is set.

ex. if gender not set, the filter will be: Test.objects.filter(categories=category, brands=brand)

def index(request):
    gender = request.GET.get('gender')
    category = request.GET.get('category')
    brand = request.GET.get('brand')

    Test.objects.filter(genders=gender, categories=category, brands=brand)
A: 
def index(request):
    gender = request.GET.get('gender', None)
    category = request.GET.get('category')
    brand = request.GET.get('brand')

results = Test.objects.filter(categories=category, brands=brand)
if gender:
    results = results.filter(genders=gender)

If gender is not specified, gender variable will set to None, so following if gender block will not be executed.

FallenAngel
This would work, but it's rather lengthy.
rebus
Manoj Govindan's answer is a shorter approach (:
FallenAngel
+1  A: 

If you realize that filter conditions can be passed in as keyword arguments the solution becomes easier to visualize. For e.g. consider the snippet below. This is a verbose way of doing it:

conditions = dict()

for filter_key, form_key in (('genders',  'gender'), ('categories', 'category'), ('brands', 'brand')):
    value = request.GET.get(form_key, None)
    if value:
        conditions[filter_key] = value

Test.objects.filter(**conditions)

Of course another way of doing this would be to use a form rather than pick up the values directly from the GET request.

Manoj Govindan
Great!! - Thanks for the answer!
pkdkk