Question

I have a Django model

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)

Now I want to search for user. Problem is when I do

Q(first_name__icontains=search_string) | Q(last_name__icontains=search_string) 

it only searches in first_name and last_name respectively. But if someone types the whole name in search bar it won't give any results as the whole name(first_name+last_name) is not contained in first_name or last_name. I don't want to change my model but dynamically query in combination of fields(first_name +last_name) on search, is there any way to do that?

Was it helpful?

Solution

if u have multiple words split by space and use istartswith. check if it is s single word or multiple, if single use your current search else split and use like below.

Q(first_name__istartswith="Firstname") | Q(last_name__istartswith="Firstname") | Q(first_name__istartswith="Lastname") | Q(last_name__istartswith="Lastname") )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top