bak*_*tin 3 django django-rest-framework
我有一个模型Foo,用作我的普通 DRF 序列化器的模型。
模型.py
class Foo(models.Model):
name = models.CharField(max_length=20)
description = models.TextField()
is_public = models.BooleanField(default=False)
Run Code Online (Sandbox Code Playgroud)
序列化器.py
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
Run Code Online (Sandbox Code Playgroud)
视图.py
class FooRetrieveAPIView(RetrieveAPIView):
queryset = Foo.objects.all()
serializer_class = FooSerializer
Run Code Online (Sandbox Code Playgroud)
现在,前端代码正在使用此端点的结果,这是如何识别下一页要显示的基础。200无论如何,我需要更改状态(现有记录)和404(不存在记录)返回的结果的结构。
实际结果(来自普通 DRF):
$ curl localhost:8000/foo/1/ # existing record
{"id": 1, "name": "foo", "description": "foo description", is_public=false}
$ curl localhost:8000/foo/2/ # non-existent record
{"detail": "Not found."}
Run Code Online (Sandbox Code Playgroud)
我想要的结果是:
$ curl localhost:8000/foo/1/
{"error": "", "foo": {"id": 1, "name": "foo", "description": "foo description", is_public=false}}
$ curl localhost:8000/foo/2/
{"error": "Some custom error message", "foo": null}
Run Code Online (Sandbox Code Playgroud)
我主要使用普通 DRF,所以事情非常简单,因此响应结构的这种定制对我来说有点新鲜。
使用的Django版本:1.9.9
使用的DRF版本:3.3.x
您可以retrieve在视图中重写方法以更新序列化器响应数据
class FooRetrieveAPIView(RetrieveAPIView):
queryset = Foo.objects.all()
serializer_class = FooSerializer
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
data = serializer.data
# here you can manipulate your data response
return Response(data)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9068 次 |
| 最近记录: |