如何使用嵌套的序列化器(具有4级嵌套)显示嵌套结果并根据子序列化器中定义的字段过滤结果?
models.py
class Level1(models.Model):
level_one_name = models.CharField(max_length=128)
class Level2(models.Model):
level_two_name = models.CharField(max_length=128)
level_one = models.ForeignKey(Level1, related_name='level1_set', on_delete=models.CASCADE)
class Level3(models.Model):
level_three_name = models.CharField(max_length=128)
level_two = models.ForeignKey(Level2, related_name='level2_set', on_delete=models.CASCADE)
class Level4(models.Model):
level_four_name = models.CharField(max_length=128)
level_three = models.ForeignKey(Level3, related_name='level3_set', on_delete=models.CASCADE)
question_type = models.IntegerField()
所需的输出: 应基于 question_type 过滤输出,可以从URL提取。例如,如果question_type = 1,那么我应该从具有question_type = 1的表 Level4 中获取所有记录。结果应采用以下格式:
[{
"level_one_name" : "l1",
"level_two" : [
{
"level_two_name" : "l2",
"level_three" : [
{
"level_three_name" : "l3",
"level_four" : [
{
"level_four_name" : ""
}]
}]
}]
}]
请提出解决此问题的优化方法。预先谢谢你。