我正在创建的模型中的一个字段用于列出其自身类型的实例。如何在django中做到这一点?我找不到有关如何执行此操作的任何文档。
这与我在说的类似,但是由于尚未定义Component类(并且可能还有其他原因),因此无法正常工作。
class Component(models.Model):
name = models.CharField()
description = models.CharField()
status_ok = models.BooleanField()
subcomponents = models.ForeignKey(Component)
一个普通的类,简要地演示了这个概念:
class Component:
def __init__(self, name, description, status_ok, *subcomponents):
self.name = name
self.description = description
self.status_ok = status_ok
self.subcomponents = []
for subcomponent in subcomponents:
if isinstance(subcomponent, Component):
self.subcomponents.append(subcomponent)
else:
raise TypeError(subcomponent)
答案 0 :(得分:3)
要引用相同的模型,请使用普通的Python语法self
,但要作为字符串,
Class Component(models.Model):
name = models.CharField()
description = models.CharField()
status_ok = models.BooleanField()
subcomponents = models.ForeignKey('self')