Django queryset - search for first and last name

I have a django application that retrieves all items from one user table. I also implemented an input search form, this is a completed query:

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') 

since you can see a query for the first search for matching items by name, and then by first name. this works until I enter the full name "firstaname lastname" or "lastname firstname", in which case there are no results. How can I modify the query to do a better search?

thanks - luke

+6
source share
3 answers

Copy / Paste From: fooobar.com/questions/344856 / ...

 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 
+8
source

You need Q objects , and you also need to split the query into separate terms (since no name will match the full string "First Name Last Name").

Here's an idea to match any first or last name starting with "Firstname" or "Lastname" in the search for "Firstname Lastname".

This is a general search - tailor your query to your specific needs!

Edit: oops, I really don't like to use shortening, because it looks confusing, but they must be ORed together, and we cannot do a more detailed version, because the number of terms is unknown.

 import operator from django.db.models import Q search_args = [] for term in request.GET['query_term'].split(): for query in ('first_name__istartswith', 'last_name__istartswith'): search_args.append(Q(**{query: term})) all_soggs = Entity.objects.filter(reduce(operator.or_, search_args)) 

To find out how to use Q objects, when searching for "First Name Last Name" the previous query is:

 Entity.objects.filter( Q(first_name__istartswith="Firstname") | Q(last_name__istartswith="Firstname") | Q(first_name__istartswith="Lastname") | Q(last_name__istartswith="Lastname") ) 
+7
source

Similar question: Request a full name in Django

 query = request.GET.get('query') entities = [] try: firstname = query.split(' ')[0] lastname = query.split(' ')[1] entities += Entity.objects.filter(firstname__icontains=firstname,lastname__icontains=lastname) entities += Entity.objects.filter(firstname__icontains=lastname,lastname__icontains=firstname) entities = set(entities) 
0
source

Source: https://habr.com/ru/post/906890/


All Articles