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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With