Django格式化查询作为特定的json

时间:2018-05-06 02:48:55

标签: python json django django-rest-framework

我正在使用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格式?

相关问题已审核:

Where to change the form of json response in django rest framework?

How to return custom JSON in Django REST Framework

Custom JSON representation of query result

Retrieving a Foreign Key value with django-rest-framework serializers

0 个答案:

没有答案