假设我有一个简单的 django 模型:
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
当我通过 django Web 框架将其中的信息显示为 JSON 时,我得到:
[{"id": 1, "title": "hello"}, {"id": 2, "title": "world"}]
如何将数组标题添加到生成的 JSON 中?就像这样:
["books" :{"id": 1, "title": "hello"}, {"id": 2, "title": "world"}]
最佳答案
所以你的客户端API要求JSON是一个对象而不是数组(当使用浏览器内置的javascript解析器解析JSON时有一个安全原理,但我忘记了原因)...
如果您的客户端 API 不介意 PaginationSerializer
添加的额外字段,您可以执行以下操作:
class BookSerializer(pagination.BasePaginationSerializer):
results_field = "books"
class BookListView(generics.ListAPIView):
model = Book
pagination_serializer_class = BookSerializer
paginate_by = 9999
这将导致:
{
'count': 2,
'next': null,
'previous': null,
'books': [
{"id": 1, "title": "hello"},
{"id": 2, "title": "world"}
]
}
[更新]
避免使用数组作为 JSON 根的安全原因是 JSON Hijacking 。基本上,聪明的黑客可以重写数组构造函数来做一些令人讨厌的事情。仅当您的 API 正在应答 GET 请求并使用 cookie 进行身份验证时才相关。
关于json - Django休息框架: How to add an array name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24433314/