【发布时间】: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