【问题标题】:Why do I get a ForeignKey constraint violation为什么我会违反 ForeignKey 约束
【发布时间】:2018-08-30 09:04:07
【问题描述】:

如下所示,我有 2 个模型通过中间模型连接,形成多对多关系。问题是,当我删除 Tender 对象时,会出现此错误。

update or delete on table "tender_details_tender" violates foreign key constraint "user_account_company_tender_id_984ea78c_fk_tender_de" on table "user_account_companyprofile_assignedTenders"
DETAIL:  Key (id)=(1) is still referenced from table "user_account_companyprofile_assignedTenders".

我认为通过在 ForeighKeys(即在中间模型中)添加 on_delete=models.CASCADE 可以解决这个问题,但显然不是。

class CompanyProfile(models.Model):
      assignedTenders = models.ManyToManyField(Tender, through='UsersTenders', related_name='UserCompanies')
      
      

# connects users to the tenders they match.		
class UsersTenders(models.Model):
    user = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, related_name='userTenderLink')
    tender = models.ForeignKey(Tender, on_delete=models.CASCADE, related_name='userTenderLink')
    sent = models.BooleanField(default=False, blank=False)
    class Meta:
        unique_together = ("user", "tender")
        
        
class Tender(models.Model):
    tenderCategory = models.ManyToManyField(Category, blank=False)       #this field holds the tender category, e.g. construction, engineering, human resources etc.
    tenderProvince = models.ManyToManyField(Province, blank=False)       #this is the province the tender was a

对于它的价值,我知道是什么导致了这个问题,但我不知道如何解决它。问题是,最初我在 CompanyProfile 模型下的 ManyToManyField 没有“through”参数,因此您可能想象 Django 创建了它自己的中间表,即“user_account_companyprofile_assignedTenders”,如错误所示。后来我决定创建自己的中间模型(即UsersTenders),因为我想要一个额外的字段,所以我必须在我的ManyToManyField(即'assignedTenders')中添加“through”参数。这工作得很好,但旧的中间模型“user_account_companyprofile_assignedTenders”没有被自动删除,我认为它是因为在更改之前已经创建了一些关系。如何在不破坏项目稳定性的情况下删除“user_account_companyprofile_assignedTenders”。

【问题讨论】:

    标签: django python-3.x django-models django-views


    【解决方案1】:

    你在数据库迁移后添加了 on_delete 吗?如果是,您是否在添加 on_delete 后进行了迁移?

    您可以尝试将 null=True 设置为所有字段,然后尝试找出导致问题的外键。

    bdw。当您设置 blank=True 时,仅表示您的表单字段不会坚持填写此字段以进行提交。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 2011-09-12
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多