I'm trying to search users by their usernames and display names.
- I have used that for the starting match.
search_obj = User.objects.exclude(user_uuid=token_user_uuid).filter(Q(display_name__istartswith=search_name)
| Q(username__istartswith=search_name)
).order_by('-created_on')[:10]
I get the answer same as I want but the problem is if the display name is William Welch
and I search for Welch
It should return that user also, but it does not return that user.
cases.
username: 123William
display name: William Welch
if search_name 12 then match
if search_name 23w then not match
if search_name Wil then match
if search_name Welc then match
if search_name elch then not match
CodePudding user response:
You can search with __icontains
[Django-doc] to look for a substring instead:
from django.db.models import Q
search_obj = (
User.objects.exclude(user_uuid=token_user_uuid)
.filter(
display_name__icontains=search_name,
username__icontains=search_name,
_connector=Q.OR,
)
.order_by('-created_on')[:10]
)
If you want to search for starting words, you can work with a regex with the __iregex
lookup [Django-doc]:
import re
from django.db.models import Q
rgx = fr'\y{re.escape(search_name)}'
search_obj = (
User.objects.exclude(user_uuid=token_user_uuid)
.filter(
display_name__iregex=rgx,
username__iregex=rgs,
_connector=Q.OR,
)
.order_by('-created_on')[:10]
)