我在 Django 中定义模型的顺序有一些问题,所以我想要这样的东西:
class Album(models.Model):
mainTrack = models.OneToOneField(Track)
class Track(models.Model):
albumID = models.ForeignKey(Album)
以这种方式,当我想运行 makemigration 命令时,django 给出了这个错误:
Track is not defined
有什么办法可以解决吗??
请您参考如下方法:
正如您已经注意到的这一行
mainTrack = models.OneToOneField(Track)
引用了 Track 但显然 Track 此时没有定义。
解决方案:
使用字符串引用 Track 模型:
mainTrack = models.OneToOneField('Track')
docs 中也提到了这一点:
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.
