How to filter DB query with OR in Django

Viewed 64

I am trying to structure a WHERE question LIKE 'Who%' OR question LIKE 'What%' SQL query from inputs of a POST request. What is the correct way to do this?

If showall POST value is True then no next filter needs to be matched. All entries returned. If showall is False then combine the next filters for the OR statement to return entries matching only of the filters provided.

https://docs.djangoproject.com/en/3.1/topics/db/queries/#complex-lookups-with-q-objects

from django.db.models import Q
def getuserlist(request):
    if request.method == "POST":
        showall = request.POST['showall']
        showfl_1 = request.POST['showfl_1']
        showfl_2 = request.POST['showfl_2']

        if showall == 'true':
            filt = Q(listing=any)
        elif showfl_1 == 'true':
            filt = Q(listing="Filtered1")
        elif showfl_2 == 'true':
            filt = filt | Q(listing="Filtered2")

        searchresult = list(User_data.objects.filter(listing=filt).values_list("Country","gender","listing").order_by('-added_date'))
   return searchresult
2 Answers

You can construct a Q object that is a disjunction of the options:

from django.http import JsonResponse

if showall != 'true':
    filters = []
    if showfl_1 == 'true':
        filters.append(('listing', 'filtered1'))
    if showfl_1 == 'true':
        filters.append(('listing', 'filtered2'))
    if not filters:
        searchresult = User_data.objects.none()
    else:
        searchresult = Q(*filters, _connector=Q.OR)
else:
    searchresult = User_data.objects.all()

searchresult = list(searchresult.values_list(
    'Country','gender','listing'
).order_by('-added_date'))
return JsonResponse({'data': searchresult})

You may try something like this

from django.db.models import Q
def getuserlist(request):
    if request.method == "POST":
        showall = request.POST['showall']
        showfl_1 = request.POST['showfl_1']
        showfl_2 = request.POST['showfl_2']
        c = {}
        if showall:
            c['listing']= Q(listing=any)
        elif showfl_1:
            c['listing']= Q(listing="Filtered1")
        elif showfl_2:
            c['listing'] = Q(listing="Filtered2")

        searchresult = list(User_data.objects.filter(**c).values_list("Country","gender","listing").order_by('-added_date'))
   return searchresult
Related