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()
您可以通过引用来完成此操作,如数据结构中的(二进制)树。