我正在使用内置的django管理站点来保存具有ManyToMany字段的模型的实例。如果我保存而不是更新管理站点中的模型而没有为ManyToMany字段设置值,则可以保存。保存模型后,我也可以返回并设置ManyToMany字段。但是,如果我尝试保存我的模型的新实例,练习,具有ManyToMany字段,Exercise.muscles,设置我得到以下错误:
(1452,'无法添加或更新子行:外键约束失败 (
vitality
。projectvitality_exercise_muscles
,约束exercise_id_refs_exercise_id_a5d4ddd6
外键(exercise_id
)参考projectvitality_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"
答案 0 :(得分:0)
经过几天的调试,我发现了这个问题。在我的代码中,我使用来自django-extensions库的UUIDField作为主键。保存练习模型的新实例时,它可以生成,设置和保存主键。但是,在保存设置了ManyToMany字段的新练习实例时,不会及时生成UUIDField。这导致Django管理员尝试将一个空/空主键(练习模型中的UUIDField)插入到连接表中,从而触发外键约束失败。