Home > database >  Django foreign key constraint on drop even thou on_delete=CASCADE
Django foreign key constraint on drop even thou on_delete=CASCADE

Time:11-24

I can't see what's wrong with this,

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
    )
    ...

When I try to delete an agenda, i.e. Agenda.objects.get(pk=2).delete() I get this problem:

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"

What is it I don't understand? I'm guessing it's something to do with the inheritance?

CodePudding user response:

This is an issue with django-polymorphic, see issues here, here and here.

You can try adding below to your AgendaResource model as a workaround:

class AgendaResource(PolymorphicModel):
    ...
    non_polymorphic = models.Manager()

    class Meta
        base_manager_name = 'non_polymorphic'
  • Related