views:

86

answers:

1

Hello

How can I do something like this :

products_list = Product.objects.all()

for key in keywords:
    products_list = products_list.filter(name__icontains=q)

This don't work.

Thank you for your help

+1  A: 

You are filtering the list with several AND statements, and you want OR statements. Try something like this:

from django.db.models import Q
products_list = Product.objects.all()
orq = None    
for key in keywords:
    thisq = Q(name__icontains=q)
    if orq:
        orq = thisq | orq
    else:
        orq = thisq
products_list = products_list.filter(orq)

You could probably clean up the above code, but the idea is to create a variable called orq that is basically Q(name__icontains='prod1') | Q(name__icontains='prod2').

Gattster
Actually this doesn't work `products_list = Product.objects.all()` and then `products_list = products_list.filter(orq)` but I can directly do `products_list = Product.objects.filter(orq)` and I work perfectly :)
Natim
Natim
I'm glad it worked for you. Good luck on your project.
Gattster