What is the best way to search in multiple fields in django?

Question:

I have the following model in my models.py, and I want to search based on its three fields.

class Profile(models.Model):
    username = models.CharField(max_length=128, null=False, blank=False, unique=True)
    password = models.CharField(max_length=128, null=False, blank=False)
    name = models.CharField(max_length=50, null=True, blank=True)
    lastname = models.CharField(max_length=50, null=True, blank=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE)

There are also three separate inputs for entering the text, one for name, one for last name, and one for username. The user should at least fill in one input, or if the input string was a part of main string, the main string should be returned.

enter image description here
This is my API, but it does not return anything, and the result list is always empty.

def search_users(request):
    if request.method == 'GET':
        try:
            to_be_searched_username = request.GET.get("username", None)
            to_be_searched_name = request.GET.get("name", None)
            to_be_searched_lastname = request.GET.get("lastname", None)

            supervisor_username = request.headers['Authorization']
            supervisor = Profile.objects.get(username=supervisor_username)
            if not((to_be_searched_name or to_be_searched_lastname) or to_be_searched_username):
                return Response({"message": "Enter a search term"}, status=status.HTTP_204_NO_CONTENT)
            else:
                results = supervisor.children.filter(
                    username__icontains=to_be_searched_username and to_be_searched_username is not None
                ).filter(
                    name__icontains=to_be_searched_name and to_be_searched_name is not None
                ).filter(
                    lastname__icontains=to_be_searched_lastname and to_be_searched_lastname is not None
                )
            return Response({'results': results}, status=status.HTTP_200_OK)
        except:
            return Response({"message": "خطا در دریافت اطلاعات"}, status=status.HTTP_400_BAD_REQUEST)

I will be grateful for any help or advice.

Asked By: Aylin Naebzadeh

||

Answers:

You can filter with:

def search_users(request):
    if request.method == 'GET':
        to_be_searched_username = request.GET.get('username')
        to_be_searched_name = request.GET.get('name')
        to_be_searched_lastname = request.GET.get('lastname')

        supervisor_username = request.headers['Authorization']
        supervisor = get_object_or_404(Profile, username=supervisor_username)
        if not (
            to_be_searched_name
            or to_be_searched_lastname
            or to_be_searched_username
        ):
            return Response(
                {"message": "Enter a search term"},
                status=status.HTTP_204_NO_CONTENT,
            )
        else:
            results = supervisor.children.all()
            if to_be_searched_username:
                results = results.filter(
                    username__icontains=to_be_searched_username
                )
            if to_be_searched_name:
                results = results.filter(name__icontains=to_be_searched_name)
            if to_be_searched_lastname:
                result = result.filter(
                    lastname__icontains=to_be_searched_lastname
                )
        return Response({'results': results}, status=status.HTTP_200_OK)
Answered By: Willem Van Onsem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.