Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Queryset for concat query fullname of first_name and last_name

I would like to do a fullname (first_name concat last_name) search/query in Django.

The following is my model:

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)    
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)    
    created_at = models.DateTimeField(auto_now_add=True)

For example we have an entry like this. first_name:"Michael", last_name:"Jackson"

I want to be able to query full name "michael jackson". If can show without case sensitive would be great as well.

This other stackoverflow question is similar but the answers is not fulfilling this particular requirement in proper Querying full name in Django. We want to be able to do a concat search.

I tried with annotate but it doesnt work

queryset = Employee.objects.annotate(fullname=Concat('first_name', 'last_name'))
search_result = queryset.filter(fullname__icontains='michael jackson')
like image 222
Axil Avatar asked Dec 09 '17 00:12

Axil


1 Answers

this worked.

from django.db.models.functions import Concat
from django.db.models import Value

queryset = Employee.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name'))
c = queryset.filter(fullname__icontains='michael jackson')
like image 154
Axil Avatar answered Oct 30 '22 18:10

Axil