Search code examples
djangodjango-modelsdjango-viewsdjango-formsdjango-queryset

django queryset - searching for firstname and lastname


i have a django app that retrieve all subjects from a single table of users. i've also implemented an input search form, this is the query performed:

all_soggs =     Entity.objects.filter(lastname__istartswith=request.GET['query_term']).order_by('lastname')
if(all_soggs.count()==0):
    all_soggs = Entity.objects.filter(firstname__istartswith=request.GET['query_term']).order_by('firstname')

as you can see the query first search for matching items by lastname, and then by firstname. this works until i insert the complete name 'firstaname lastname' or 'lastname firstname', in this case there's no results. how can i modify the query to make a better search?

thanks - luke


Solution

  • Copy/paste from: https://stackoverflow.com/a/17361729/1297812

    from django.db.models import Q 
    
    def find_user_by_name(query_name):
       qs = User.objects.all()
       for term in query_name.split():
         qs = qs.filter( Q(first_name__icontains = term) | Q(last_name__icontains = term))
       return qs