0

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.

1243916142
  • 365
  • 6
  • 17

1 Answers1

0

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

....

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 reverse lookup of foreign keys

It is called foreign key reverse lookup

babygame0ver
  • 447
  • 4
  • 16
  • But how about it there is a EModel? I don't think the x_set helps the post. – 1243916142 Dec 26 '17 at 11:36
  • you have to go back from D to A by all items of C in D then B in C and then A to B. Have you check the link in the answer it will help you. – babygame0ver Dec 26 '17 at 11:44
  • Sorry I have fired wrong query when you will do first query it will return you the set of all possibilities. then iterate through one by one in another model – babygame0ver Dec 26 '17 at 11:46