带有rest-framework序列化器的Django-haystack给出结果None

时间:2014-11-16 16:46:34

标签: python django django-rest-framework django-haystack

我尝试使用django-haystack在我的应用中添加基于elasticsearch的搜索。我使用django-rest-framework来构建API。以下是我的索引:

class ArtistIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, model_attr='name')

    def get_model(self):
        return Artist

这是我的观点:

def search(request):
    q = request.GET.get('q', '')
    if q is '':
        return Response(status=status.HTTP_400_BAD_REQUEST)
    all_results = SearchQuerySet().models(Artist).filter(content=Clean(q))
    serializer = ArtistSerializer(all_results, many=True)
    print serializer.data
    return Response(status=status.HTTP_200_OK)

我的序列化器:

class ArtistSerializer(serializers.ModelSerializer):
    class Meta:
        model = Artist
        fields = (
            'name',
            'type',
            'gender',
            'begin_life',
            'end_life',
        )

但是,当我点击端点时,print语句会打印出类似这样的内容:

[{'name': None, 'type': None, 'gender': None, 'begin_life': None, 'end_life': None}, {'name': None, 'type': None, 'gender': None, 'begin_life': None, 'end_life': None}, {'name': None, 'type': None, 'gender': None, 'begin_life': None, 'end_life': None}, {'name': None, 'type': None, 'gender': None, 'begin_life': None, 'end_life': None}, {'name': None, 'type': None, 'gender': None, 'begin_life': None, 'end_life': None}]

有人可以告诉我我做错了什么吗?

感谢。

1 个答案:

答案 0 :(得分:3)

我找到了更好的序列化数据的方法。我现在正在使用它:

from django.core import serializers

-- snippet --

def search(request):
    q = request.GET.get('q', '')
    if q is '':
        return Response(status=status.HTTP_400_BAD_REQUEST)
    all_results = SearchQuerySet().filter(content=Clean(q))
    serializer = serializers.serialize("json", [q.object for q in all_results])
    print serializer
    return Response(status=status.HTTP_200_OK)

现在,我可以搜索多个模型而无需担心序列化数据:)

结果数据如下:

{
    "fields": {
        "name": "Megadeth",
        "end_life": "",
        "gid": "a9044915-8be3-4c7e-b11f-9e2d2ea0a91e",
        "gender": "",
        "type": "2",
        "begin_life": "1983-6-"
    },
    "model": "InQusic.artist",
    "pk": 975773
}

所以,现在我可以在我的客户端区分结果。