Reputation: 26896
I have three tables, names A
, B
, C
:
class A(models.Model):
name = models.CharField(max_length=12)
class B(models.Model):
name = models.CharField(max_length=12)
a = models.ForeignKey(to=A)
class C(models.Model):
name = models.CharField(max_length=12)
email = models.EmailField()
b = models.ForeignKey(to=B)
I want get the bellow data:
[
{"name":"a1",
"data":[{
"name":"b1",
"data":[
{"name":"c1",
"data":{"c1_name":"c1_name", "c1_id":"c1_id"}
},
{"name":"c2",
"data":{"c2_name":"c2_name", "c2_id":"c2_id"}
}
]
},
{
"name":"b2",
"data":[
{"name":"c1",
"data":{"c1_name":"c1_name", "c1_id":"c1_id"}
},
{"name":"c2",
"data":{"c2_name":"c2_name", "c2_id":"c2_id"}
}
]
}
]
}
]
You see, there is three-level data, if there is only table A and B, I can multi-table connection query:
B.objects.filter(a='search_id')
But now there is three tables, and you see the table C
's email is not contain in the query data.
How to realize this requirement in my scenario?
Upvotes: 0
Views: 222
Reputation: 3038
As @Brian H. is pointing out in the comments, you can chain foreign keys with __
.
In your case you could get the data with
C.objects.filter(b__a='search_id').values('id', 'name', 'b__name', 'b__a__name')
You can then loop through the data and build the list in the format you require.
Upvotes: 1