繁体   English   中英

如何在 Django 中使用 OR 过滤 DB 查询

[英]How to filter DB query with OR in Django

我正在尝试从 POST 请求的输入中构造一个WHERE question LIKE 'Who%' OR question LIKE 'What%' SQL 查询。 这样做的正确方法是什么?

如果showall POST 值为True ,则不需要匹配下一个过滤器。 所有条目返回。 如果showallFalse ,则组合OR语句的下一个过滤器以返回仅与提供的过滤器匹配的条目。

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

您可以构造一个Q object ,它是选项的析取:

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

你可以试试这样的

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM