A
A
Artem Kislenko2017-03-27 07:29:53
Django
Artem Kislenko, 2017-03-27 07:29:53

How to implement search by full name, having two separate fields in the database (first_name, last_name)?

Hello?
How to canonically release search.
There is a search query (it is not known in advance what will be entered)
There are two fields first_name,
last_name The FIRST NAME value is in firt_name, the LAST NAME value is in last_name.
Is it correct to break the search query by spaces and look for results for each word, or is there some more "direct" implementation for DJANGO?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
javedimka, 2017-03-27
@webwork

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

stackoverflow.com/questions/9009635/django-queryse...
Q objects
But in general, if it's not too late, I would make one field full_name, first_name and last_name would be received through model methods, and searching through icontains and there would be no problems.

E
Elvis, 2017-03-27
@Dr_Elvis

I don’t know how for django, but for sql I would do the query like this (you need to break it with a space):

SELECT * FROM table
WHERE last_name = 'ФАМИЛИЯ' AND firt_name= 'ИМЯ'

or like this (no need to break with a space):
SELECT * FROM table
WHERE concat(last_name, ' ', firt_name) = 'ФАМИЛИЯ ИМЯ'

and it’s even better to bring it to one register, so that it doesn’t give an empty list if the register doesn’t match somewhere:
SELECT * FROM table
WHERE lower(concat(last_name, ' ', firt_name)) = lower('ФАМИЛИЯ ИМЯ')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question