我正在尝试使用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数据得到正确的响应。我做错了什么?
答案 0 :(得分:47)
您还可以使用不需要型号的APIView
class MyOwnView(APIView):
def get(self, request):
return Response({'some': 'data'})
和
urlpatterns = [
url(r'^my-own-view/$', MyOwnView.as_view()),
]
您已将自定义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