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