首页 > 解决方案 > 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 格式?

审查的相关问题:

django rest框架中json响应的形式在哪里改变?

如何在 Django REST 框架中返回自定义 JSON

查询结果的自定义 JSON 表示

使用 django-rest-framework 序列化程序检索外键值

标签: pythonjsondjangodjango-rest-framework

解决方案


推荐阅读