我有四个模型如下:
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")
现在我想获得波纹管数据:
[
{"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",
}
]
}
]
}
]
}
]
请注意,value
和image
键值是我自己添加的。
我知道使用Django-Rest-Framework可以得到如下数据:
[
{
"id":1,
"name":"a1",
"bs":[
{
"id":1,
"name":"b1",
"cs":[
"id":1,
"name":"c1",
"ds":[
{
"id":1,
"name":"d1",
}
]
]
}
]
}
]
但我怎样才能获得我的需求数据?
我还尝试首先查询AModel实例,然后查询AModel实例的bs,然后执行下一步,但我发现这太复杂了,不是一种简单方便的方法。
答案 0 :(得分:0)
这不是实际的代码,而是伪代码,它会给你一个想法。
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 - >; A通过制作每个集合然后迭代它们。点击此处了解更多信息
Django reverse lookup of foreign keys
它被称为外键反向查找