Question and Answer django queryset

I have a model that I want to filter with a search term, which is usually a name. However, in my database first_name and last_name are two separate fields.

eg.

search_term = 'Will Sm'

db_persons entry: first_name = 'Will', last_name = 'Smith'

A search query will be able to retrieve this entry.

How can i achieve this?

db_persons.objects.filter(__?__)

UPDATE:

Looking for a way to combine fields and request a concatenated result without raw sql

+3
source share
2 answers

A simple solution would be to add another complete_name field in your model. In save you update this field by concatenating the first_name and last_name fields without a space (you need to remove all spaces from the result of the concatenation). Then you will make a request in this field using search_term , but with spaces also separate.

A simple example to give you a general idea:

 class Person(models.Model): first_name = CharField(...) last_name = CharField(...) complete_name = CharField(...) def save(self, *args, **kwargs): complete_name = '%s%s' % (self.first_name, self.last_name) self.complete_name = complete_name.replace(' ', '') super(Person, self).save(*args, **kwargs) results = Person.objects.filter(complete_name__icontains=search_term.replace(' ', '')) 
+2
source

If you want to search in the first and last name, you can simply use:

 db_persons.objects.filter(first_name='Will', last_name='Smith') 

Use Q objects if you want to search in first_name OR last_name:

 from django.db.models.query_utils import Q db_persons.objects.filter(Q(first_name='will') | Q(last_name='will')) 

Refresh according to comment . A simple solution might look like this:

 search_string = 'will smith' query_list = search_string.split() db_persons.objects.filter(Q(first_name__in=query_list) | Q(last_name__in=query_list)) 

If you are using mysql, you can use search .

+6
source

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


All Articles