Skip to content

IntegrityError deleting SensorLocation referenced by dailyavg2023 (missing FK in Django model) #160

Description

@VinneyJ

Labels: bug, data-model, admin
Linked Sentry: SENSORSAFRICA-API-140 — https://code-for-africa.sentry.io/issues/7570022076/
Environment: production

Summary

Deleting a SensorLocation in admin fails with:
update or delete on table "sensors_sensorlocation" violates foreign key constraint "fk_sensorlocation" on table "sensors_dailyavg2023"

Root cause

sensors_dailyavg2023 has a Postgres-level FK to sensors_sensorlocation that is not declared as a ForeignKey field in the Django model. Django's deletion collector doesn't know the relationship exists, so it doesn't cascade/null it before issuing the DELETE — Postgres correctly rejects it.

Fix

Add the missing ForeignKey field to the Django model with an explicit on_delete (needs a product decision: CASCADE vs PROTECT vs SET_NULL — does deleting a location wipe historical daily averages, or should locations with historical data be undeletable?).

To check

Whether dailyavg2024/dailyavg2025 have the same gap. if so, fix should apply to all year-tables, not just 2023.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions