How to add multiple "OR" queries in Django

I have 2 models, Item and Category, the model Item has category field as a foreign key

In my views.py I get a list of queries from a POST request queries = ['category1', 'category2', 'category3', ...]

I don’t know the number of the queries I will get from the request, and I want to filter the Item model based on category field

I tried this

from django.db.models import Q
from .models import Item, Category
from django import views

class myView(views.View):
    def post(self, request):
        queries = request.POST.get('queries', '')
        if queries:
            queriesList = []
            queries = queries.split(',')  # queries = ['category1', 'category2', ....]
            for query in queries:
                queriesList.append(Q(category__icontains=query))
            queryset = Item.objects.filter(*queriesList) # this will do AND but won't do OR
            # I tried: queryset = Item.objects.filter([q | Q() for q in queriesList]) but it didn't work

Also I tried queryset = Item.objects.filter(category__in=queries)
but it’s case sensitive

>Solution :

You can use Q.OR as _connector:

from django.db.models import Q

from django import views

from .models import Category, Item


class myView(views.View):
    def post(self, request):
        queries = request.POST.get('queries', '')
        if queries:
            queryset = Item.objects.filter(
                *[Q(category__icontains=query) for query in queries.split(',')],
                _connector=Q.OR
            )

searching is however normally done through a GET request, such that the search query appears in the URL, and thus the URL can be copied, bookmarked, etc. with the search query included.

Leave a Reply