0

我正在使用内置的 django 管理站点来保存具有 ManyToMany 字段的模型的实例。如果我在管理站点中保存而不是更新模型而不为 ManyToMany 字段设置值,它可以很好地保存。我也可以在保存模型后返回并设置 ManyToMany 字段,这很有效。但是,如果我尝试保存具有 ManyToMany 字段、Exercise.muscles 设置的模型的新实例,我会收到以下错误:

(1452, '无法添加或更新子行:外键约束失败 ( vitality. projectvitality_exercise_muscles, CONSTRAINT exercise_id_refs_exercise_id_a5d4ddd6FOREIGN KEY ( exercise_id) REFERENCES 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"
4

1 回答 1

0

经过几天的调试,我发现了问题。在我的代码中,我使用来自 django-extensions 库的 UUIDField 作为主键。当保存一个新的练习模型实例时,它能够生成、设置和保存主键。但是,在保存设置了 ManyToMany 字段的新练习实例时,不会及时生成 UUIDField。这导致 Django 管理员尝试将空/空主键(练习模型中的 UUIDField)插入到连接表中,从而触发外键约束失败。

于 2013-06-05T03:38:22.147 回答