[英]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.我正在尝试从 POST 请求的输入中构造一个
WHERE question LIKE 'Who%' OR question LIKE 'What%'
SQL 查询。 What is the correct way to do this?这样做的正确方法是什么?
If showall
POST value is True
then no next filter needs to be matched.如果
showall
POST 值为True
,则不需要匹配下一个过滤器。 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.如果
showall
为False
,则组合OR
语句的下一个过滤器以返回仅与提供的过滤器匹配的条目。
https://docs.djangoproject.com/en/3.1/topics/db/queries/#complex-lookups-with-q-objects 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
You can construct a Q
object that is a disjunction of the options:您可以构造一个
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})
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.