如何在Django中获取自定义嵌套数据?
我有以下四个模型:
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",
}
]
}
]
}
]
}
]
注意,值
和图像
键值是我自己添加的。
我知道使用Django-Rest-Framework可以得到如下数据:
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?
我也尝试过先查询AModel实例,先查询AModel实例的bs,然后再执行下一个查询,但是我发现这太复杂了,不是一种简单方便的获取方法
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.
不是真正的代码,而是伪代码,可以为您提供帮助。
It is not the actual code but pseudo code which will give you the idea.
data_of_C_in_D = D.C_set # gives all value of C in D
Data_of_B_in_C = for i in data_of_C_in_D:
B.i_set #gives all value of C in B
....
类似地,您也可以从D- ->通过对它们中的每一个进行集合,然后对其进行迭代来进行。在此处查看更多
Similarly you can go from D -- > A by making the set of each of them and then iterating over them. Check here for more
称为外键反向查找