I would like to know, how I could use django-rest-framework to provide a paginated json result from a get request q=thisterm
.
I understand the haystack end of things using SearchQuerySet.filter(content=q)
however how do I serialize and create an api view with this queryset. I am not sure which viewset to use nor the basic logic behind what I would need to do on the rest end.
Any help would be appreciated.
Thanks
After a lot of trial and error, i have found the right combination! Here is a start.
Define a serializer: serializers.py
class DotaSearchSerializer(serializers.Serializer):
text = serializers.CharField()
name = serializers.CharField()
quality = serializers.CharField()
type = serializers.CharField()
rarity = serializers.CharField()
hero = serializers.CharField()
image = serializers.CharField()
desc = serializers.CharField()
Create the view: views.py
class DotaSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = DotaSearchSerializer
permission_classes = (IsAuthenticated,)
authentication_classes = (SessionAuthentication, BasicAuthentication)
def get_queryset(self, *args, **kwargs):
request = self.request
queryset = EmptySearchQuerySet()
if request.GET.get('q') is not None:
query = request.GET.get('q')
queryset = SearchQuerySet().filter(content=query)
return queryset
Please note you might want to clean the input and perform other security checks.
Route it: urls.py
router.register(r'search', api_views.DotaSearchViewSet, base_name='search')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With