diff --git a/action/models.py b/action/models.py index 0bf43dc..aeb0eb0 100644 --- a/action/models.py +++ b/action/models.py @@ -1,4 +1,5 @@ from django.db import models, connection +from django.db.models import Max from user.models import User, Institution from django.core.exceptions import ValidationError @@ -23,13 +24,31 @@ class State(models.Model): class StateDefinition(models.Model): institution = models.ForeignKey(Institution, on_delete=models.CASCADE) - order = models.AutoField(primary_key=True) + + order = models.PositiveIntegerField(default=0) state = models.CharField(max_length=50) class Meta: + ordering = ['order'] constraints = [ models.UniqueConstraint(fields=['institution', 'state'], name='unique_institution_state') ] + def save(self, *args, **kwargs): + if not self.pk: + # set the order to be last + max_order = StateDefinition.objects.filter(institution=self.institution).aggregate(Max('order'))['order__max'] + self.order = (max_order or 0) + 1 + super().save(*args, **kwargs) + + + def delete(self, *args, **kwargs): + institution = self.institution + order = self.order + super().delete(*args, **kwargs) + # Adjust the order of other instances + StateDefinition.objects.filter(institution=institution, order__gt=order).update(order=models.F('order') - 1) + + def __str__(self): return f"{self.institution.name} - {self.state}"