vikrant vikrant - 1 month ago 19
Python Question

When using Q objects in django queryset for OR condition error occured

I want to use filter with OR condition in django.
For this i want to use Q objects.
My code is this

def product(request):
try:

proTitle = request.GET.get('title')
ProDescription = request.GET.get('description')
funAria = request.GET.get('funAria')
femaleReq = request.GET.get('femaleReq')

except:
pass


list0 = []
result = Product.objects.filter(Q(title__contains=proTitle ) | Q(description__contains=ProDescription ) | Q(functional_area__contains=funAria ) | Q(female_candidate=femaleReq ))

for res in result:

list0.append(res.project_id)
data ={'title result':list0}
return HttpResponse(json.dumps(data))



return HttpResponse(json.dumps(data), content_type='application/json')


When pass all value that is
proTitle,ProDescription,funAria,femaleReq

it working fine.
If anyone value is going to none it encounter a error
Cannot use None as a query value

Why this error occured when i am using OR operator into my queryset

I am also try this

result = Project.objects.filter(title__contains=proTitle) | Project.objects.filter(description__contains=ProDescription ) | Project.objects.filter(functional_area__contains=funAria ) | Project.objects.filter(female_candidate=femaleReq )


but same error occured

`def product(request):
attributes = (('title', 'title__contains'),
('description', 'description__contains'),
('funAria', 'functional_area__contains'),
('femaleReq', 'female_candidate'))

query_filter = Q() # initialize

for get_param, kw_arg in attributes:
get_param = request.GET.get(get_param)
if get_param:
query_filter |= Q(**{ kw_arg: get_param })

result = Product.objects.filter(query_filter)

list0 = []


for res in result:

list0.append(res.project_id)
data ={'title result':list0}
return HttpResponse(json.dumps(data))



return HttpResponse(json.dumps(data), content_type='application/json')`


THis also did not help me

2ps 2ps
Answer

Your error seems to mean that one of your values is None:

def product(request):
    try:

        proTitle = request.GET.get('title')
        ProDescription = request.GET.get('description')
        funAria = request.GET.get('funAria')
        femaleReq = request.GET.get('femaleReq')

    except:
        pass

    allQs = Q()
    if proTitle is not None: 
        allQs |= Q(title__contains=proTitle )
    if ProDescription is not None:
        allQs |= Q(description__contains=ProDescription )         
    if funAria is not None:
        allQs |= Q(functional_area__contains=funAria )
    allQs |= Q(female_candidate=femaleReq )
    list0 = []
    result = Product.objects.filter(allQs)
    for res in result:

        list0.append(res.project_id)
    data ={'title result':list0}
    return HttpResponse(json.dumps(data))
Comments