Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name 'Q' is not defined [closed]

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
like image 228
James Smith Avatar asked Nov 29 '22 23:11

James Smith


1 Answers

You should import the Q class before using it:

from django.db.models import Q
like image 115
Selcuk Avatar answered Dec 01 '22 14:12

Selcuk