Reputation: 501
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:
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
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
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