python - Django 将查询格式化为特定的 json
问题描述
我正在使用 Django Rest 框架为现有客户端创建 API。我的 model.py 是这样的:
class Unit(models.Model):
name = models.CharField(max_length=250, null=True, blank=True)
summary = models.TextField(null=True, blank=True)
location = models.ForeignKey(Location, null=True, blank=True)
class Location(models.Model):
name = models.CharField(max_length=250, null=True, blank=True)
# refrenced in response json as category_name
def __unicode__(self):
return unicode(self.name)
def __str__(self):
return unicode(self.name)
我的 API 应该是这样的,我无法在客户端更改格式:
{
"data": [
{
"category_name": "Block A -1",
"items": [
{
"id": "26",
"name": "negar",
"summary": ""
},
{
"id": "27",
"name": "art coffee",
"summary": ""
}
]
},
{
"category_name": "Block B 2",
"items": [
{
"id": "14",
"name": "kid house",
"summary": ""
},
{
"id": "15",
"name": "teen bookstore",
"summary": "",
}
]
}
]
}
我读到必须将APIView与自定义序列化程序一起使用,但找不到将查询格式化为给定格式的方法。是否有任何正确的方法或简单的技巧将查询格式化为空间 json 格式?
审查的相关问题:
解决方案
推荐阅读
- apache - Mac 上的 XAMPP 虚拟主机通配符子域
- excel - Excel VBA 字典项连接
- r - 使用 grep 或 dplyr 有条件地删除行并替换其他行?
- javascript - 下拉列表未列出从 React js 中的 https://disease.sh/ 导入的国家/地区
- python - 遍历 URL 时如何解决动态 DOM 问题?
- git - 在 Prezto ZSH 中为 git 函数自定义完成
- java - Observable 没有返回打印出来的值
- anaconda - wget 在可访问的文件上给出 403
- tomcat - 如何使 Tomcat 7 提示输入客户端证书
- javascript - SAP UI5中数据的绑定