Hi im writing a search view for searching for alumni within a prepopulated database using django. It will search a prepopulated database for alumni based on the users input and return that back to the users via the template. Error says Name 'Q' is not defined
def alumni_search(request, form_class=Find_AlumniForm, template_name='alumni/Find_Alumni.html'):
form = None
if request.method == 'POST':
#do search
form = form_class(request.POST)
if form.is_valid():
results = search(form.cleaned_data)
if results:
return render(request, template_name, {'form': form, 'Alumni': results})
else:
form = form_class()
return render(request, template_name, {'form': form})
def search(search_data):
q = Q()
results = None
searcher = alumni_search(search_data)
for key in search_data.iterkeys():
dispatch = getattr(searcher, 'search_%s' % key)
q = dispatch(q)
if q and len(q):
results = alumni.objects.filter(q).select_related()
#.order_by('-pk')
else:
results = []
return results
class AlumniSearch(object):
def __init__(self, search_data):
self.__dict__.update(search_data)
def search_keywords(self, q):
if self.keywords:
words = self.keywords.split()
first_name_q = Q()
last_name_q = Q()
for word in words:
first_name_q = first_name_q | Q(first_name__icontains=word)
last_name_q = last_name_q | Q(last_name__icontains=word)
keyword_q = first_name_q | last_name_q
q = q & keyword_q
return q
You should import the Q
class before using it:
from django.db.models import Q
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With