I'm creating a search functionality where we can search based of
first_name
,last_name
,username
.it should filter all matches( if at least anyone fields match it should consider ) users except login users.this is what I have done but I'm searching for an efficient Django queryset.
if search_name is not None and len(search_name) >= 3: search_obj_1 = User.objects.filter(first_name__iexact=search_name).exists() search_obj_2 = User.objects.filter(last_name__iexact=search_name).exists() if search_obj_1: search_obj_1 = User.objects.filter(Q(first_name__iexact=search_name)) &User.objects.filter(~Q(id=logged_user_id)) search_obj_2 = User.objects.filter(Q(last_name__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj_3 = [] search_obj = list(chain(search_obj_1, search_obj_2, search_obj_3)) elif search_obj_2: search_obj_1 = [] search_obj_2 = User.objects.filter( Q(last_name__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj_3 = User.objects.filter( Q(username__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj = list( chain(search_obj_2, search_obj_3, search_obj_1)) else: search_obj_1 = [] search_obj_2 = [] search_obj_3 = User.objects.filter( Q(username__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj = list( chain(search_obj_3, search_obj_1, search_obj_2))
so is there any better way do the same thing.
CodePudding user response:
You can try something like this (using the union operator |
) :
search_obj = User.objects.exclude(id=logged_user_id).filter(
Q(first_name__iexact=search_name)
| Q(last_name__iexact=search_name)
| Q(username__iexact=search_name)
)