我有一个包含9个表的MySQL数据库。它们都以某种方式相关,但我无法连接外键。例如,当我尝试python manage.py migrate时,我的两个表格出现错误:
class Release(models.Model):
release_ID = models.CharField(max_length=25, primary_key =True)
releaseversion = models.CharField(max_length=25)
model_ID = models.ForeignKey(Model, on_delete=models.CASCADE) #comes from Model class
class Subrelease(models.Model):
subrelease_ID = models.CharField(max_length=25)
release_ID = models.ForeignKey('Release', blank =True) #comes from Release class
subreleaseversion = models.CharField(max_length=25)
如何从类Release发出主键,release_ID也是类Subrelease中的ForeignKey release_ID?任何帮助将非常感激。谢谢。
运行迁移后,我在cmd中得到了这个:
django.db.utils.InternalError: (1829, "Cannot drop column 'id': needed in a foreign
key constraint 'app_subrel_release_ID_id_8e08450_fk_app_release_id' of table
'db.app_subrelease'")
更新 这好/可以吗?迁移到DB时,我没有任何错误?
class Release(models.Model):
#release_ID = models.CharField(max_length=25, primary_key =True)THIS WILL BE OUR PRIMARY KEY MADE BY DJANGO
releaseversion = models.CharField(max_length=25)
model = models.ForeignKey(Model, on_delete=models.CASCADE) #comes from Model class model_ID
class Subrelease(models.Model):
#subrelease_ID = models.CharField(max_length=25) THIS WILL BE OUR PRIMARY KEY MADE BY DJANGO
release = models.ForeignKey(Release, on_delete=models.CASCADE ) #comes from Release class release_ID
subreleaseversion = models.CharField(max_length=25)
答案 0 :(得分:2)
class B(models.Model):
name = models.ForeignKeyField(A, to_field="name", db_column="name")
创建外键后,您可以按如下方式访问值和相关实例:
>>> b = B.objects.get(id=1)
>>> b.name_id # the value stored in the 'name' database column
>>> b.name # the related 'A' instance
参考: this answer