英文:
How to return custom JSON response in UpdateAPIView?
问题
I was trying to return some custom message after the user completes updating data after submission. How can I do this in the UpdateApiView?
class DetailUpdateView(generics.UpdateAPIView):
permission_classes = (permissions.IsAuthenticated,)
lookup_field = "pk"
serializer_class = DetailSerializers
def get_queryset(self):
data = Data.objects.all()
return data
I want a response something like this:
{
"message": "success",
"status": 200,
"details": [
{
"id": 2,
"DOB": "2012-10-21",
"cycle_length": "10",
"category": "2",
"child_dob": null,
"Period": "10",
"Last_cycle": "2012-10-21",
"userid": 2
}
]
}
英文:
I was trying to return some custom message after user complete updated data after submit. How can i do this in UpdateApiView?
class DetailUpdateView(generics.UpdateAPIView):
permission_classes = (permissions.IsAuthenticated,)
lookup_field = "pk"
serializer_class = DetailSerializers
def get_queryset(self):
data = Data.objects.all()
return data
I want response something like this:
{
"message": "success",
"status": 200,
"details": [
{
"id": 2,
"DOB": "2012-10-21",
"cycle_length": "10",
"category": "2",
"child_dob": null,
"Period": "10",
"Last_cycle": "2012-10-21",
"userid": 2
},
答案1
得分: 4
你可以像这样覆盖UpdateAPIView
中的update
方法:
class DetailUpdateView(generics.UpdateAPIView):
permission_classes = (permissions.IsAuthenticated,)
lookup_field = "pk"
serializer_class = DetailSerializers
def get_queryset(self):
data = Data.objects.all()
return data
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
result = {
"message": "success",
"details": serializer.data,
"status": 200,
}
return Response(result)
注意:代码部分不需要翻译。
英文:
you can override update
from UpdateAPIView
like this:
class DetailUpdateView(generics.UpdateAPIView):
permission_classes = (permissions.IsAuthenticated,)
lookup_field = "pk"
serializer_class = DetailSerializers
def get_queryset(self):
data = Data.objects.all()
return data
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
result = {
"message": "success",
"details": serializer.data,
"status": 200,
}
return Response(result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论