我试图覆盖序列化程序的响应消息(返回数据)。以下是我的示例代码。
models.py
from django.db import models
class MyModel(models.Model):
name = models.charField()
email = models.EmailField()
phone = models.charField()
serializer.py
from rest_framework import serializers
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'name', 'email', 'phone')
def validate(self, data):
'''
Some validation here
'''
return data
views.py
from rest_framework import generics
class MyModelList(generics.ListCreateAPIView):
queryset = MyModel.objects.all().order_by('-id')
serializer_class = MyModelSerializer
这里,当我尝试发布数据时,序列化程序以json格式返回响应
{
'id': 2,
'name': 'myname',
'email': 'mayname@example.com',
'phone': 8569874587,
}
但是如果帖子成功,我想像这样返回自定义json响应。
{
'success' : 'data posted successfully',
}
伙计们如何为自定义消息覆盖此内容,请为此帮助我,它会非常完整,提前致谢。
答案 0 :(得分:2)
覆盖ListCreateAPIView
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(
{"Success": "Data posted successfully"},
status=status.HTTP_201_CREATED,
headers=headers)