我试图实现这个答案Response来为我的所有类创建一个自定义基ModelViewSet类。我的问题在于retrieve功能。如果Id我正在寻找的实例没有找到,我似乎无法Response用我修改的response_format. 它仍然给出默认响应。我应该把我的if病情改成什么?
views.py:
class ResponseInfo(object):
def __init__(self, **args):
self.response = {
"message": args.get('message', 'success'),
"error": args.get('error', ),
"data": args.get('data', []),
}
class LanguageView(viewsets.ModelViewSet):
def __init__(self, **kwargs):
self.response_format = ResponseInfo().response
super(LanguageView, self).__init__(**kwargs)
permission_classes = [permissions.DjangoModelPermissions]
queryset = Language.objects.all()
serializer_class = LanguageSerializer
def list(self, request, *args, **kwargs):
# call the original 'list' to get the original response.
response_data = super(LanguageView, self).list(request, *args, **kwargs)
# customize the response data.
self.response_format['data'] = response_data.data
if not response_data.data:
self.response_format['message'] = 'List is empty.'
self.response_format['error'] = response_data.status_code
return Response(self.response_format)
def retrieve(self, request, *args, **kwargs):
response_data = super(LanguageView, self).retrieve(request, *args, **kwargs)
self.response_format['data'] = response_data.data
if not response_data.data:
self.response_format['message'] = 'Instance not found.'
self.response_format['error'] = response_data.status_code
return Response(self.response_format)
找到实例时的 JSON 响应。例如http://127.0.0.1:8000/languages/1/:
{
"message": "success",
"error": null,
"data": {
"id": 1,
"name": "English",
"icon": "http://127.0.0.1:8000/media/language_icons/English.png",
"xml": "http://127.0.0.1:8000/media/-",
"abbreviation": "En"
}
}
"error"没有错误时是否可以不显示变量?对于这种情况,当列表不为空并且找到搜索的实例时。
莫回无
相关分类