Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#26641 closed Uncategorized (invalid)

Unable to concatenate 2 fields when filtering

Reported by: FoxPotato Owned by: nobody
Component: Database layer (models, ORM) Version: 1.9
Severity: Normal Keywords: QuerySet.extra
Cc: foxpotato5@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The docs said I should file a ticket when using the extra API.

I just need a way to use the icontains field lookup on 2 fields at once, for example the full name (first_name + last_name) of a user.

I managed it using the extra API like this:

User.objects.extra(where=['upper(concat(first_name, " ", last_name)) LIKE upper(%s)'], params=[query])

Change History (1)

comment:1 by Simon Charette, 8 years ago

Resolution: invalid
Status: newclosed

You should be able to use the Concat function for this purpose:

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

User.objects.annotate(
    name=Concat('first_name', Value(' '), 'last_name'),
).filter(name__icontains=value)

Or simply use Q objects:

from django.db.models import Q

User.objects.annotate.filter(
    Q(first_name__icontains=value) | Q(last_name__icontains=value),
)
Last edited 8 years ago by Simon Charette (previous) (diff)
Note: See TracTickets for help on using tickets.
Back to Top