I have four model as bellow:
class AModel(models.Model):
name = models.CharField(max_length=11)
class BModel(models.Model):
name = models.CharField(max_length=11)
a = models.ForeignKey(AModel, related_name="bs")
class CModel(models.Model):
name = models.CharField(max_length=11)
b = models.ForeignKey(BModel, related_name="cs")
class DModel(model.Model):
name = models.CharField(max_length=11)
c = models.ForeignKey(CModel, related_name="ds")
Now I want to get the bellow data:
[
{"name":"a1",
"value":1,
"image":"xxxxx.png",
"children":[
{"name":"b1",
"value":1,
"image":"xxxxx.png",
"children":[
{"name":"c1",
"value":1,
"image":"xxxx.png",
"children":[
{"name":"d1",
"value":1,
"image":"xxxx.png",
}
]
}
]
}
]
}
]
note, the value
and image
key-value are add by myself.
I know use the Django-Rest-Framework can get the data like:
[
{
"id":1,
"name":"a1",
"bs":[
{
"id":1,
"name":"b1",
"cs":[
"id":1,
"name":"c1",
"ds":[
{
"id":1,
"name":"d1",
}
]
]
}
]
}
]
But how can I get my requirement data?
I also tried query the AModel instance first, the forloop the AModel instance's bs, and then do the next, but I find that is too complex, not a simple and convenient way to get it.