1

I am using Django Rest framework to create API for existing clients. my model.py is st like this:

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)

My API should be like this and I cannot change formatting in client side:

{
"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": "",
            }
        ]
    }

]
}

I read that must use APIView with customized serializer but cannot find way to format query into given format. Is there any correct way or simple trick to format queries as spacial json format?

related questions reviewd:

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

Bheid
  • 306
  • 3
  • 11
  • So basically your client cannot read JSON. A program consuming JSON, per [the standard](https://tools.ietf.org/html/rfc7159) *“MUST accept all texts that conform to the JSON grammar”*. Therefore it's not JSON you want to output, but your own custom format that happens to be a subset of JSON. You cannot expect a standard JSON generator to generate your own format, you'll probably have to write your own formater. – spectras May 06 '18 at 03:06

0 Answers0