我正在使用内置的 django 管理站点来保存具有 ManyToMany 字段的模型的实例。如果我在管理站点中保存而不是更新模型而不为 ManyToMany 字段设置值,它可以很好地保存。我也可以在保存模型后返回并设置 ManyToMany 字段,这很有效。但是,如果我尝试保存具有 ManyToMany 字段、Exercise.muscles 设置的模型的新实例,我会收到以下错误:
(1452, '无法添加或更新子行:外键约束失败 (
vitality
.projectvitality_exercise_muscles
, CONSTRAINTexercise_id_refs_exercise_id_a5d4ddd6
FOREIGN KEY (exercise_id
) REFERENCESprojectvitality_exercise
(exercise_id
))')
我的 mysql 表设置为 INNODB。
我的模型如下:
class Muscle(models.Model):
def format(self):
return "name:{0}:".format(self.name)
def __unicode__(self):
return unicode(self.name)
muscle_id = UUIDField(primary_key = True)
name = models.CharField(max_length=30, blank=False, default="")
medical = models.CharField(max_length=150, blank=True, default="")
description = models.TextField(blank=True, default="")
class Exercise(models.Model):
def format(self):
return "name:{0}".format(self.name)
def __unicode__(self):
return unicode(self.name)
ISOLATION_TYPE = "isolation"
COMPOUND_TYPE = "compound"
FULL_BODY_TYPE = "full"
EXERCISE_TYPES = (
(ISOLATION_TYPE, "Isolation"),
(COMPOUND_TYPE, "Compound"),
(FULL_BODY_TYPE, "Full Body")
)
UPPER_BODY_GROUP = "upper"
LOWER_BODY_GROUP = "lower"
GROUP_CHOICES = (
(UPPER_BODY_GROUP, "Upper Body"),
(LOWER_BODY_GROUP, "Lower Body")
)
exercise_id = UUIDField(primary_key=True)
name = models.CharField(max_length=30, default="", blank=False)
description = models.TextField(blank=True, default="")
group = models.CharField(max_length=255,
choices=GROUP_CHOICES,
blank=False,
default=UPPER_BODY_GROUP)
exercise_type = models.CharField(max_length=255,
choices=EXERCISE_TYPES,
blank=False,
default=ISOLATION_TYPE)
muscles = models.ManyToManyField('Muscle', blank=True, null=True)
class Meta:
verbose_name = "Exercise"
verbose_name_plural = "Exercises"