我正在编写一个搜索视图,用于使用django搜索预填充数据库中的校友。它将根据用户输入搜索预先填充的校友数据库,并通过模板将其返回给用户。错误名称' Q'未定义
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