如何在Django REST Framework中返回自定义JSON

时间:2016-01-26 16:38:53

标签: python json django django-rest-framework

我正在尝试使用get_queryset返回自定义json,但总是得到404 error作为响应。

class TestViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Test.objects.all()
    serializer_class = TestSerializer

    def get_queryset(self):
        if self.request.method == "GET":
            content = {'user_count': '2'}
            return HttpResponse(json.dumps(content), content_type='application/json')

如果我从def开始删除所有内容,我将使用标准的json数据得到正确的响应。我做错了什么?

2 个答案:

答案 0 :(得分:47)

如果您不需要ModelViewSet并且只想在GET请求上使用自定义JSON

您还可以使用不需要型号的APIView

class MyOwnView(APIView):
    def get(self, request):
        return Response({'some': 'data'})

urlpatterns = [
    url(r'^my-own-view/$', MyOwnView.as_view()),
]

使用ModelViewSet

您已将自定义JSON放入get_queryset,这是错误的。如果你想使用ModelViewSet,这本身就足够了:

class TestViewSet(viewsets.ModelViewSet):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

ModelViewSet附带.list().retrieve().create().update().destroy()的默认实施。哪些可供您根据需要覆盖(自定义)

.retrieve()和/或.list()

中的ModelViewSet返回自定义JSON

E.g。在检索单个对象时覆盖.retrieve()以返回自定义视图。我们可以查看default implementation which looks like this

def retrieve(self, request, *args, **kwargs):
    instance = self.get_object()
    serializer = self.get_serializer(instance)
    return Response(serializer.data)

以此作为返回自定义JSON的示例:

class TestViewSet(viewsets.ModelViewSet):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

    def retrieve(self, request, *args, **kwargs):
        return Response({'something': 'my custom JSON'})

    def list(self, request, *args, **kwargs):
        return Response({'something': 'my custom JSON'})

答案 1 :(得分:0)

有两种方法可以使用 ModelViewSet

基于类的视图中自定义响应
  

解决方案1: views.py

中自定义
class StoryViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.AllowAny,)
    queryset = Story.objects.all()
    serializer_class = StorySerializer

    def retrieve(self, request, *args, **kwargs):
        # ret = super(StoryViewSet, self).retrieve(request)
        return Response({'key': 'single value'})

    def list(self, request, *args, **kwargs):
        # ret = super(StoryViewSet, self).list(request)
        return Response({'key': 'list value'})
  

解决方案2:自定义 serializers.py (我推荐此解决方案)

class StorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Story
        fields = "__all__"

    def to_representation(self, instance):
        ret = super(StorySerializer, self).to_representation(instance)
        # check the request is list view or detail view
        is_list_view = isinstance(self.instance, list)
        extra_ret = {'key': 'list value'} if is_list_view else {'key': 'single value'}
        ret.update(extra_ret)
        return ret