Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading