Dynamic number of Django filters for querying objects

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 does not work.

+3
source share
1 answer

You are filtering a list with multiple 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)

Perhaps you could clear the above code, but the idea is to create a variable with a name orqthat is basically Q(name__icontains='prod1') | Q(name__icontains='prod2').

+2
source

Source: https://habr.com/ru/post/1727458/


All Articles