rest框架多个唯一查询集

时间:2016-10-31 12:30:33

标签: django django-rest-framework

我有一个facets方法,它采用搜索查询集,在django rest框架中将这两个输出序列化的最佳方法是什么?

# This only works for results
class SearchResultsSerializer(serializers.BaseSerializer):
    def to_representation(self, obj):
        return {
            'a': obj.a,
            'b': obj.b
        }

目标输出:

{
    "count": 0,
    "next": "http://localhost:8000/q=Cupertino",
    "previous": null,
    "results": []
    "facets": [] # <--- can't figure out how to get this
}

1 个答案:

答案 0 :(得分:0)

事实证明,使用api_view实现这一点是微不足道的,但是你放弃了视图集中的细节,比如分页等。

from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import permissions


@api_view(['GET'])
@permission_classes((permissions.AllowAny,))
def my_custom_view(request):
    queryset = build_a_queryset(request.GET.get('q', ''))
    serialized_results = ResultsSerializer(queryset, many=True)
    serialized_facets = FacetsSerializer(queryset, many=True)

    return Response({
        'results': serialized_results.data,
        'facets': serialized_facets.data,
        # need to paginate on your own here
    })