2👍
You may set the defaults of the get
method to something other than None
, say empty string:
proTitle = request.GET.get('title', '')
ProDescription = request.GET.get('description', '')
funAria = request.GET.get('funAria', '')
femaleReq = request.GET.get('femaleReq', '')
This is however likely to return all results in the DB when using __contains
.
Otherwise you may build the Q functions discarding all None
values.
Use this as a guideline: How to dynamically compose an OR query filter in Django?
0👍
You can build the Q
object in a loop, discarding all values that are none. Note that after consideration, it appears that your except
will never be reached because get
will simply return None
if the Get parameter is not present. You can thus replace the try
with an if
.
The following code assumes that you simply want the unset values to be ignored in the filter.
(This is untested–let me know if you have any issues.)
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_value = request.GET.get(get_param)
if get_value:
query_filter |= Q(**{ kw_arg: get_value })
result = Product.objects.filter(query_filter)
- [Answered ]-How can I order query results by which field matched in Django?
- [Answered ]-Django getting database fields with one query
- [Answered ]-Django login AttributeError: 'AnonymousUser' object has no attribute '_meta'
- [Answered ]-Analogs for Placeholder from Django-CMS or Streamfield from Wagtail without cms itself
- [Answered ]-Django/ Python- should I run makemigrations on a local branch, or only on master?
0👍
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')
someIntValue = request.GET.get('someIntValue')
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 )
if someIntValue is not None:
allQs |= Q(some_int_value__gte=someIntValue) # no need to convert someIntValue to an int here as long as you are guaranteed it is unique.
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))
- [Answered ]-Django unable to connect to database.
- [Answered ]-How to access MEDIA_ROOT files within the view
- [Answered ]-Django model with multiple choices