diff --git a/action/models.py b/action/models.py index b28f7af..25be31d 100644 --- a/action/models.py +++ b/action/models.py @@ -1,22 +1,33 @@ from django.db import models, connection from user.models import User, Institution - - -class StateDefinition(models.Model): - institution = models.ForeignKey(Institution, on_delete=models.CASCADE) - order = models.PositiveIntegerField() - state = models.CharField(max_length=255) - - def __str__(self): - return f"{self.institution.name} - {self.state}" +from django.core.exceptions import ValidationError class State(models.Model): date = models.DateTimeField(auto_now_add=True) institution = models.ForeignKey(Institution, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) - state = models.CharField(max_length=255) + state = models.CharField(max_length=50) snapshot_uuid = models.UUIDField() + class Meta: + unique_together = ('institution', 'state') + def __str__(self): return f"{self.institution.name} - {self.state} - {self.snapshot_uuid}" + +class StateDefinition(models.Model): + institution = models.ForeignKey(Institution, on_delete=models.CASCADE) + order = models.AutoField(primary_key=True) + state = models.CharField(max_length=50) + + def clean(self): + if not StateDefinition.objects.filter(institution=self.institution, state=self.state).exists(): + raise ValidationError(f"The state '{self.state}' is not valid for the institution '{self.institution.name}'.") + + def save(self, *args, **kwargs): + self.clean() + super().save(*args, **kwargs) + + def __str__(self): + return f"{self.institution.name} - {self.state}"