blaziken105
blaziken105

Reputation: 501

Use django rest api for filtering usernames starting with

This is probably a noob doubt. I am using the django rest framework and a react native front end. I am performing a search for usernames. So I want to return usernames similar to the ones typed in such as if the user starts typing, Ji then it should return:

  1. Jim
  2. Jimmy ...

I am using the following to try and retreive the usernames but only when the full username is entered the data is returned.

class SearchForUsers(generics.ListAPIView):
    serializer_class = UserAndProfileSerializer
    def get_queryset(self):
       uname = self.kwargs['username']
       queryset = User.objects.all()
       queryset = queryset.filter(username=uname)

    return queryset

What alternative to queryset.filter should be used to get usernames and details on the fly?

Upvotes: 1

Views: 1589

Answers (2)

Sayse
Sayse

Reputation: 43320

You need to check if the username contains what the user types, preferably icontains so its case insensitive

queryset = queryset.filter(username__icontains=uname)

If you just need to find out if the user name starts with the text, then use startswith or istartswith

queryset = queryset.filter(username__istartswith=uname)

Upvotes: 4

Hugo Brilhante
Hugo Brilhante

Reputation: 606

You might consider using the SearchFilter. Something like this:

class SearchForUsers(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserAndProfileSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('username')

Upvotes: 0

Related Questions