【发布时间】:2018-01-26 09:40:32
【问题描述】:
所以我有一张桌子叫书。我正在使用模型视图集,但我希望我的响应具有附加响应。
在我的 Book 表中:
class Book(models.Model):
book = models.CharField(max_length=10, blank=True, null=True)
author = models.CharField(max_length=10, blank=True, null=True)
序列化器
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'book', 'author')
查看
class BookViewSet(viewsets.ModelViewSet):
permission_classes = [AllowAny]
queryset = Book.objects.all()
serializer_class = BookSerializer
post 或 update 方法后的返回结果将返回用户创建/更新的数据/字段。但我想补充一下。
当前结果
{
"id": 1,
"book": "hello",
"author": "helloauth",
}
我想要的结果
{
"id": 1,
"book": "hello",
"author": "helloauth",
"message": "You have successfully create a book",
"status": "200",
}
我现在拥有的自定义代码仅显示消息:
自定义视图
class BookViewSet(viewsets.ModelViewSet):
permission_classes = [AllowAny]
queryset = Book.objects.all()
serializer_class = BookSerializer
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({"message": "You have successfully create a book",
"status": "200"}, headers=headers)
如何让它结合/显示在一起?
【问题讨论】:
标签: django django-rest-framework