Integrating django-haystack with django-rest-framework?
Asked Answered
S

1

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

Slash answered 31/8, 2014 at 8:17 Comment(0)
S
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')
Slash answered 1/9, 2014 at 1:28 Comment(4)
this was extremely helpful. Thanks. Can you advise me on how to add the result count to the outputed JSON?Brownell
Have a look at Haystack for Django REST Framework: github.com/inonit/drf-haystackHighwayman
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?Conias
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.Soppy

© 2022 - 2024 — McMap. All rights reserved.