首页 > 解决方案 > ForeignKey 更新不会在 Django 在 Postgres 中创建的表上级联

问题描述

这是我尝试更新外键在相关表中查看的“父”表中的值时遇到的错误:

ERROR:  update or delete on table "product" violates foreign key constraint "pd_family_product_guid_ada83db3_fk_product_guid" on table "pd_family"
DETAIL:  Key (guid)=(902d30b8-26ba-ea11-a812-000d3a5bbb60) is still referenced from table "pd_family".
SQL state: 23503

这就是我的模型:

class Product(models.Model):
    guid = models.UUIDField(primary_key=True)
    product = models.CharField(max_length=10)
    year = models.IntegerField()
    previous_product_name = models.CharField(max_length=10)

class StandardProductFieldsMixin(models.Model):
    product_guid = models.ForeignKey('Product', on_delete=models.CASCADE, db_column='product_guid')

    class Meta:
        abstract = True

class ActiveFieldMixin(models.Model):
    active = models.BooleanField()

    class Meta:
        abstract = True

class Family(StandardProductFieldsMixin, ActiveFieldMixin):
    new_code = models.IntegerField(null=True)
    code = models.DecimalField(max_digits=20, decimal_places=2)
    title = models.CharField(max_length=255)
    desc = models.TextField(null=True)
    fam_desc = models.TextField(null=True)

当我尝试更改 in 的值时guidProduct我的期望是它也会自动更改它Family。我试图用类似的东西来改变它:

UPDATE product
SET guid = '902D30B8-26BA-EA11-A812-000D3A5BBB6B'
WHERE guid = '902D30B8-26BA-EA11-A812-000D3A5BBB60'

我想我的印象是错误的。我需要在模型中做一些额外的事情吗?查看了类似的文档on_update,但没有看到 an**options或作为models.ForeignKey.

从我在阅读了一个多小时后收集到的信息来看,如果我想要这种功能,我只需要在 Postgres 手册中添加它,删除约束并用ON UPDATE CASCADE.

标签: djangopostgresqldjango-models

解决方案


显然我的印象是错误的:

https://stackoverflow.com/a/61648910/3123109

听起来 Django 模型迁移既不实现ON DELETE也不实现ON UPDATE数据库CASCADES选项。我想我需要进入数据库并在那里实现它们。


推荐阅读