Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating django-haystack with django-rest-framework?

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

like image 990
Deep Avatar asked Aug 31 '14 08:08

Deep


Video Answer


1 Answers

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')
like image 194
Deep Avatar answered Sep 19 '22 08:09

Deep