【问题标题】:Django foreign key constraint on drop even thou on_delete=CASCADE即使你 on_delete=CASCADE 也可以删除 Django 外键约束
【发布时间】:2022-01-01 23:35:04
【问题描述】:

我看不出这有什么问题,

class Agenda(models.Model):
    ...

class AgendaResource(PolymorphicModel):
    agenda = models.ForeignKey(
        Agenda, related_name="resources", on_delete=models.CASCADE
    )
    comment = models.TextField(null=True)

class PreemptiveMeasureResource(AgendaResource):
    resource = models.ForeignKey(
        PreemptiveMeasure, on_delete=models.SET_NULL, null=True
    )
    ...

当我尝试删除议程时,即Agenda.objects.get(pk=2).delete() 我遇到了这个问题:

update or delete on table "school_health_agendaresource" violates foreign key constraint "school_health_preemp_agendaresource_ptr_i_222e2e2c_fk_school_he" on table "school_health_preemptivemeasureresource"
DETAIL:  Key (id)=(2) is still referenced from table "school_health_preemptivemeasureresource"

什么是我不明白的?我猜这与继承有关?

【问题讨论】:

    标签: django postgresql django-orm


    【解决方案1】:

    这是django-polymorphic 的问题,请参阅问题hereherehere

    您可以尝试将以下内容添加到您的 AgendaResource 模型中作为解决方法:

    class AgendaResource(PolymorphicModel):
        ...
        non_polymorphic = models.Manager()
    
        class Meta
            base_manager_name = 'non_polymorphic'
    

    【讨论】:

    • 非常感谢!你为我节省了大量时间,出于某种原因,即使你在谷歌上搜索Polymorphic inheritance delete,我也没有跌跌撞撞地走上正确的轨道
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多