Reputation: 2901
Is there a way to implement a search view in my DRF API? For example, I use the following code on my site to allow the user to enter keywords into a search bar and return results.
class SearchListView(ListView):
model = User
template_name = 'search/results.html'
def get_context_data(self, *args, **kwargs):
context = super(SearchListView, self).get_context_data(*args, **kwargs)
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self, *args, **kwargs):
user_qs = super(SearchListView, self).get_queryset(*args, **kwargs)
query = self.request.GET.get('q')
if query:
user_qs = self.model.objects.filter(
Q(username__icontains=query)
)
return user_qs
Is there a way to do this in DRF to use for my API?
Thank you in advance!
Upvotes: 2
Views: 8086
Reputation: 20986
Sure thing, this is what filtering is for.
Django REST framework documentation already provides similar example. Have a look at http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters for detail implementation.
Upvotes: 1