大量的試驗和錯誤之後,我已經找到了正確的組合!這是一個開始。
定義串行: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()
創建視圖: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
請注意,您可能需要清潔的輸入並執行其他安全檢查。
路線是:urls.py
router.register(r'search', api_views.DotaSearchViewSet, base_name='search')
,這是非常有用的。謝謝。你能告訴我如何將結果計數添加到輸出的JSON嗎? – 2015-07-27 23:07:03
查看Haystack for Django REST Framework:https://github.com/inonit/drf-haystack – Daviddd 2016-07-05 06:11:22
您從HayStack的SearchQuerySet獲得所需的結果嗎? 當使用HayStack視圖(在搜索表單的情況下)或者是否存在任何性能差異時,是否遵循同樣的機制? – 2017-01-30 10:08:15