devicehub-django/action/models.py

55 lines
2 KiB
Python
Raw Normal View History

2024-11-30 07:38:19 +00:00
from django.db import models, connection
2024-12-03 18:00:26 +00:00
from django.db.models import Max
2024-11-30 07:38:19 +00:00
from user.models import User, Institution
2024-12-01 20:47:10 +00:00
from django.core.exceptions import ValidationError
2024-11-30 07:38:19 +00:00
class State(models.Model):
date = models.DateTimeField(auto_now_add=True)
2024-12-06 00:30:31 +00:00
institution = models.ForeignKey(Institution, on_delete=models.SET_NULL, null=True)
2024-11-30 07:38:19 +00:00
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
2024-12-01 20:47:10 +00:00
state = models.CharField(max_length=50)
2024-11-30 07:38:19 +00:00
snapshot_uuid = models.UUIDField()
2024-12-01 20:54:22 +00:00
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)
2024-12-01 20:47:10 +00:00
2024-11-30 07:38:19 +00:00
def __str__(self):
return f"{self.institution.name} - {self.state} - {self.snapshot_uuid}"
2024-12-01 20:47:10 +00:00
class StateDefinition(models.Model):
institution = models.ForeignKey(Institution, on_delete=models.CASCADE)
2024-12-03 18:00:26 +00:00
order = models.PositiveIntegerField(default=0)
2024-12-01 20:47:10 +00:00
state = models.CharField(max_length=50)
2024-12-01 20:54:22 +00:00
class Meta:
2024-12-03 18:00:26 +00:00
ordering = ['order']
2024-12-01 22:46:04 +00:00
constraints = [
models.UniqueConstraint(fields=['institution', 'state'], name='unique_institution_state')
]
2024-12-01 20:47:10 +00:00
2024-12-03 18:00:26 +00:00
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)
2024-12-01 20:47:10 +00:00
def __str__(self):
return f"{self.institution.name} - {self.state}"