Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中创建嵌套模型_Python_Django - Fatal编程技术网

Python 如何在django中创建嵌套模型

Python 如何在django中创建嵌套模型,python,django,Python,Django,级别有很多问题,每个问题有一个级别。这棵树从那里继续生长 + Level - Question + Level - Question + Level - Question + Level - Question + Level - Question + Level - Question

级别有很多问题,每个问题有一个级别。这棵树从那里继续生长

+ Level
  - Question
     + Level
         - Question
              + Level 
         - Question
              + Level 
         - Question
              + Level 
  - Question
     + Level
         - Question
              + Level 
         - Question
              + Level 
         - Question
              + Level

您应该使用这里解释的递归关系

例如:

models.py

class Question(models.Model):
name = models.CharField(max_length=100)
mother_level = models.ForeignKey('Level', blank=True, null=True)

enter code hereclass Level(models.Model):
name = models.CharField(max_length=100)
mother_question = models.ForeignKey('Question', blank=True, null=True)

将两个ForeignKey添加到您的问题模型中,第一个添加到级别模型,第二个添加到问题模型本身,如下所示:

class Question(models.Model):
    parent = models.ForeignKey('self',related_name='childs',null=True)
    level =  models.ForeignKey('level')
    ...

通过这种方式,您可以通过过滤没有父级和指定级别实例的问题来查找第一级问题,然后您可以通过以下方式查找每个问题的子级:
questionInstance.childs.all()

您可以通过引用来完成此操作,如数据结构中的(二进制)树。