这可能是一个数据库设计问题,但我想不出更好的办法。在其他几个模型中,我有这些模型:
class User(models.Model):
name = models.CharField( max_length=40 )
# some fields omitted
bands = models.ManyToManyField( Band )
和
class Band(models.Model):
creator = models.ForeignKey( User )
# some fields omitted
name = models.CharField( max_length=40 )
基本上,我有一个用户实体,它与一个乐队实体有很多对多的关系。不同之处在于,我想要一个特殊的用户,他在网站上“创建”了乐队,拥有特殊的编辑能力。所以我继续前进,并添加了一个名为 creator 的 ForeignKey。代码无法运行,因为 Band 在源代码中位于 User 之后。所以我转发了声明的 class Band(models.Model): pass
。可悲的是,这似乎不是一个好主意,因为现在 Band 是唯一没有在 django 管理中显示任何界面元素的模型(Bands 模型在那里,只是无法编辑)。
我的问题是,我应该对模型进行哪些更改才能使其正常工作? (如果有的话)
最佳答案
参见:http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey ,它说:
If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
关于python - 前向声明 - django 中没有管理页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1194723/