如何在Django中获取自定义嵌套数据? [英] How can I get the custom nested data in Django?

查看:69
本文介绍了如何在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

Django

称为外键反向查找

这篇关于如何在Django中获取自定义嵌套数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆