From 56a225109b17b78e6cdc7db02e20ff024a659bdf Mon Sep 17 00:00:00 2001 From: Hanne Moa Date: Thu, 19 Aug 2021 11:21:21 +0200 Subject: [PATCH] Prevent an incident from having relations with itself --- .../0004_incidentrelation_prevent_loop.py | 18 ++++++++++++++++++ src/argus/incident/models.py | 7 +++++++ 2 files changed, 25 insertions(+) create mode 100644 src/argus/incident/migrations/0004_incidentrelation_prevent_loop.py diff --git a/src/argus/incident/migrations/0004_incidentrelation_prevent_loop.py b/src/argus/incident/migrations/0004_incidentrelation_prevent_loop.py new file mode 100644 index 000000000..7a18cb115 --- /dev/null +++ b/src/argus/incident/migrations/0004_incidentrelation_prevent_loop.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2.5 on 2021-08-19 09:19 + +from django.db import migrations, models +import django.db.models.expressions + + +class Migration(migrations.Migration): + + dependencies = [ + ('argus_incident', '0003_incident_level'), + ] + + operations = [ + migrations.AddConstraint( + model_name='incidentrelation', + constraint=models.CheckConstraint(check=models.Q(('incident1', django.db.models.expressions.F('incident2')), _negated=True), name='incidentrelation_prevent_loop'), + ), + ] diff --git a/src/argus/incident/models.py b/src/argus/incident/models.py index b02d8668f..f0fea63ca 100644 --- a/src/argus/incident/models.py +++ b/src/argus/incident/models.py @@ -359,6 +359,13 @@ class IncidentRelation(models.Model): type = models.ForeignKey(to=IncidentRelationType, on_delete=models.PROTECT, related_name="incident_relations") description = models.TextField(blank=True) + class Meta: + constraints = [ + models.CheckConstraint( + check=~models.Q(incident1=models.F("incident2")), name="incidentrelation_prevent_loop" + ), + ] + def __str__(self): return f"Incident #{self.incident1.pk} {self.type} #{self.incident2.pk}"