如何自定义Mixin中的API从检索功能中自定义响应
我是Django的初学者,我已经用Mixin编写了基于类的API视图。功能很简单,即获取给定ID.IM的数据,粘贴了以下代码。
class GenericAPi(generics.GenericAPIView,mixins.ListModelMixin,mixins.RetrieveModelMixin):
serializer_class=ArticleSerializer
queryset=Article.objects.all()
lookup_field="id"
def get(self,request,id):
if id:
data=self.retrieve(request)
return Response({"data":data.data,"status":data.status_code})
else:
return self.list(request)
这是我得到的响应
{“ id”:5,“ title”:“ loream”,“ wurs”:“ me”}
然后,我导航到Mixin中的检索功能,以对响应进行一些更改。
def retrieve(self, request, *args, **kwargs):
print('Retrieving')
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response({"result":serializer.data})
然后我打电话给API,但仍然得到同样的回应。 如何自定义检索函数本身中的响应。
我需要这样的回应。
{“结果”:{“ id”:5,“ title”:“ loream”,“作者”:“ ipsum”}}}
I'm a beginner to Django, i have written a class-based API view with mixin. the functionality is simple i.e fetch the data of the given id.Im pasting the code below.
class GenericAPi(generics.GenericAPIView,mixins.ListModelMixin,mixins.RetrieveModelMixin):
serializer_class=ArticleSerializer
queryset=Article.objects.all()
lookup_field="id"
def get(self,request,id):
if id:
data=self.retrieve(request)
return Response({"data":data.data,"status":data.status_code})
else:
return self.list(request)
this is the response I'm getting
{"id":5,"title":"loream","author":"me"}
then I navigate to the retrieve function in the mixin, to make some changes in the response.
def retrieve(self, request, *args, **kwargs):
print('Retrieving')
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response({"result":serializer.data})
and then I make a call to API, but still, I'm getting the same response.
How to customize the response in the retrieve function itself.
I need response like this.
{"result":{"id":5,"title":"loream","author":"ipsum"}}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您不必在
retievemodelmixin
中自定义检索
函数。I think you don't have to customize
retrieve
function in theRetrieveModelMixin
.