Django空表上的重复键异常

时间:2018-07-16 13:14:04

标签: django orm

我有以下模型:

帐户

class User(auth_models.AbstractBaseUser):
    user_id = id_field.PrimaryIDField()
    email = models.EmailField(_("email address"), unique=True, blank=False, db_index=True)
    created = models.DateTimeField(_("date joined"), auto_now_add=True, editable=False)
    modified = models.DateTimeField(_("date modified"), auto_now=True)

    class Meta:
        verbose_name = _("user")
        verbose_name_plural = _("users")

用户

class AccountUser(approve_delete_model.ApproveDeleteModel):
    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    user = models.ForeignKey("User", on_delete=models.CASCADE)
    created = models.DateTimeField(_("date joined"), auto_now_add=True, editable=False)
    modified = models.DateTimeField(_("date modified"), auto_now=True)

    class Meta:
        verbose_name = _("account user")
        verbose_name_plural = _("account users")
        ordering = ["account", "user"]
        unique_together = (("user", "account"), )

AccountUser

我尝试通过以下实体在用户和帐户之间建立多对多关系:

AccountUser.objects.all()

调用<QuerySet []>时,结果为account = Account.objects.all()[0] user = User.objects.all()[0] (据称这意味着数据库为空)

然后我选择了第一个用户和第一个帐户,如下所示:

account

userAccountUser.objects.create(account=account, user=user) 现在都填充了一个有效值。然后,我尝试如下创建它们之间的关系:

duplicate key value violates unique constraint "app_accountuser_user_id_account_id_ase17b5v_uniq"
DETAIL:  Key (user_id, account_id)=(cc9d26c9-b6d7-4d0f-b68b-8f80178a64aa, 7978c6b3-9c40-458b-bcb2-8e4ad3092929) already exists.

但是随后我得到一个完整性异常:

foreach (XElement level1Element in XElement.Load(@"your_file.xml").Elements("appointment-nbr"))
{
    foreach (XElement level2Element in level1Element.Elements("slot"))
    {
        Console.WriteLine(level1Element.Attribute("slot-start").Value);
    }
}

这怎么可能违反对空表的唯一约束?

基础数据库是PostgreSQL。

0 个答案:

没有答案