Tom Finet Tom Finet - 1 year ago 62
reST (reStructuredText) Question

How to return all user instances with same first name or last name as in url django rest?

I am building a django rest api as the backend for an android app. I am implementing a search feature in the android client which should pass the query string; which could either be the first name, last name, both, or the email, to the backend to search the user model for any matching instances and return them to be displayed in a recycler view on the client side.

The way my url is built client side looks like this:

@GET("users/search/{name}")
Call<List<User>> searchUsers(@Path("name") String name);


The urls.py for this endpoint looks like this server side:

url(r'^search/(?P<username>.+)/$', user_views.UserSearchListView.as_view(), name="user_search"),


The view which maps to the is url looks like this:

class UserSearchListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('firstName', 'lastName', 'email')


When I test my API with postman, no matter what string I put in the url, all the users are returned, instead of only the relevant ones. How do I fix this so that only the users with matching first name, last name or email are returned?

Answer Source

Doesn't look like you're using filters.SearchFilter correctly.

# views.py
class UserSearchListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('firstName', 'lastName', 'email')

# urls.py
url(r'^search/$', user_views.UserSearchListView.as_view(), name="user_search"),

Then to request a search over the users, you would request the url:

/users/search/[email protected]

Which would return all users whose firstName, lastName or email contain the string "@example.com". Check up on the SearchFilter docs for more info on how this works and how you should customise searching and filtering. http://www.django-rest-framework.org/api-guide/filtering/#searchfilter

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download