12

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

1 Answer 1

14

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')
Sign up to request clarification or add additional context in comments.

4 Comments

this was extremely helpful. Thanks. Can you advise me on how to add the result count to the outputed JSON?
Have a look at Haystack for Django REST Framework: github.com/inonit/drf-haystack
You get your required results from getting HayStack's SearchQuerySet? Is this the same mechanism followed when using a HayStack View(In case of Search Forms) or are any performance differences are possible?
Instead of return queryset, should instead do the following: return self.queryset.filter(pk__in=queryset.values_list('pk', flat=True)) While returning queryset may work in some cases, this isn't how the haystack's queryset intended to be used. For example, Deep's code would fail when the permission_classes is set to DjangoModelPermissions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.