为什么会收到ForeignKey约束违规

时间:2018-08-30 09:04:07

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

如下所示,我有2个通过中介模型连接的模型,以形成ManyToMany关系。问题是,当我删除一个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”而不破坏我的项目的稳定性。

1 个答案:

答案 0 :(得分:0)

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

您可以尝试对所有字段设置null = True,然后尝试找出哪个外键导致了问题。

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

相关问题