Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

python - How to filter DB query with OR in Django

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...