gpt4 book ai didi

python - Django IntegrityError 更改外键

转载 作者:行者123 更新时间:2023-12-02 00:35:54 24 4
gpt4 key购买 nike

我有一个模型 LucyGuide,它通过 OneToOneField 扩展了 Django 的 User 模型:

class LucyGuide(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)

还有一个 Company 模型,它有一个名为 lucy_guide 的字段,它是 UserForeignKey型号:

class Company(models.Model):
lucy_guide = models.ForeignKey(User)

我想把这个改成

class Company(models.Model):
lucy_guide = models.ForeignKey(LucyGuide)

但是,当我实现此更改并进行和运行迁移时,我遇到了 IntegrityError:

django.db.utils.IntegrityError: insert or update on table "lucy_web_company" violates foreign key constraint "lucy_web_company_lucy_guide_id_de643702_fk_lucy_web_"
DETAIL: Key (lucy_guide_id)=(461) is not present in table "lucy_web_lucyguide".

这个问题类似于IntegrityError Insert or update on table "orders_order" violates foreign key constraint " ;好像我在将它们引用为外键之前创建了 LucyGuide 对象。

解决此问题的最佳方法是什么?是否需要在 shell 中编写一系列命令来创建这些用户?

更新

在 shell 中环顾四周,似乎 Django 仍然期望 ForeignKey 具有相同的数字 id,即使模型已更改(来自 用户LucyGuide)。以下是 Userid,它们也是 LucyGuide:

In [11]: lucy_guide_users = [user for user in User.objects.all() if hasattr(user, 'lucyguide')]

In [16]: [user.id for user in lucy_guide_users]
Out[16]: [12, 8, 461, 497, 500, 471, 475, 495]

请注意,这包含错误中 461id。然而,LucyGuideid 很简单

In [17]: [guide.id for guide in LucyGuide.objects.all()]
Out[17]: [1, 2, 3, 4, 5, 6, 7, 8]

似乎解决这个问题的方法是更改​​ LucyGuide 的主键,但似乎来自 What is the best approach to change primary keys in an existing Django app?这是一个非常复杂的过程。有没有更简单的方法?

最佳答案

您不能简单地更改外键的目标。对于每个现有公司,您需要将 lucy_guide_id 从相关用户的 id 更改为相关的 lucy_guide 的 id。 Django 不能为你做这个。

您可以分几步完成迁移。首先,添加一个新的外键并创建一个迁移

class Company(models.Model):
lucy_guide = models.ForeignKey(User)
new_lucy_guide = models.ForeignKey(LucyGuide, blank=True, null=True)

接下来,创建一个 data migration填充 new_lucy_guide 字段。

然后您可以删除 lucy_guide 字段,并创建一个迁移。

class Company(models.Model):
new_lucy_guide = models.ForeignKey(LucyGuide, blank=True, null=True)

最后,您可以重命名您的字段并创建一个迁移:

class Company(models.Model):
lucy_guide = models.ForeignKey(LucyGuide, blank=True, null=True)

关于python - Django IntegrityError 更改外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com