【问题标题】:psycopg2.IntegrityError: duplicate key value violates unique constraint DETAIL: Key (id)=(19) already existspsycopg2.IntegrityError:重复键值违反唯一约束详细信息:键(id)=(19)已经存在
【发布时间】:2019-12-14 22:23:48
【问题描述】:

我没有手动设置主键。怎么会这样?


class Image(models.Model):
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to='attack_images', blank=True, null=True)
    source_url = models.URLField(blank=True,null=True)
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True)
    slug = models.SlugField(blank=True,null=True)

在我 5 年的 Django 编程中,我从未遇到过这个错误。我无法通过查看我的代码和回溯来判断出了什么问题。有什么问题?如果我需要发布更多代码,请告诉我。提前致谢。任何帮助表示赞赏。

【问题讨论】:

  • 尝试通过python manage.py migrate修复它
  • 没有要应用的迁移

标签: python django


【解决方案1】:

您正试图在您的保存方法中保存您的子模型。

self.image.save(
                os.path.basename(self.source_url),
                File(open(result[0], 'rb'))
                )

因此,您在调用 super 的保存方法之前保存您的模型。在调用 super 的 save 方法之前,你应该设置你的图像但不要保存它。

self.image = os.path.basename(self.source_url),File(open(result[0], 'rb'))

【讨论】:

  • 你从哪里得到result
  • 你可以检查问题,我没有复制整个问题,只有要更改的行...
  • 试过attack_image_object.image = img_filename, File(img_temp)。同样的错误
  • 哦,是的,在模型中。谢谢。我在看第一部分。尝试您的解决方案。如果可行,+10
  • 这有帮助,虽然现在我得到“AttributeError: 'tuple' object has no attribute '_committed'”
【解决方案2】:

我猜一个可能的解决方案是:

./manage.py migrate appname zero

用您的应用程序名称修改 appname。 然后:

python manage.py migrate --run-syncdb

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 2020-03-27
    • 2022-01-14
    相关资源
    最近更新 更多