models.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from django.conf import settings
  2. from django.core.exceptions import ValidationError
  3. from django.db import models
  4. from .validators import less_than_one
  5. class AbstractItem(models.Model):
  6. name = models.CharField(max_length=130)
  7. description = models.TextField(blank=True)
  8. class Meta:
  9. abstract = True
  10. class Cost(AbstractItem):
  11. """ A monthtly cost we have to pay
  12. """
  13. price = models.PositiveIntegerField()
  14. def used(self):
  15. sharing_costs = CostUse.objects.filter(resource=self)
  16. existing_uses_sum = sum(
  17. sharing_costs.values_list('share', flat=True))
  18. return existing_uses_sum
  19. class Good(AbstractItem):
  20. """ A good, which replacement is provisioned
  21. """
  22. price = models.PositiveIntegerField()
  23. provisioning_duration = models.PositiveSmallIntegerField(
  24. choices=settings.PROVISIONING_DURATIONS)
  25. class AbstractUse(models.Model):
  26. share = models.FloatField(validators=[less_than_one])
  27. service = models.ForeignKey('Service')
  28. class Meta:
  29. abstract = True
  30. def clean(self):
  31. if (self.resource.used() + self.share) > 1:
  32. raise ValidationError(
  33. "Cannot use more than 100% of {})".format(self.resource))
  34. class CostUse(AbstractUse):
  35. resource = models.ForeignKey(Cost)
  36. class GoodUse(AbstractUse):
  37. resource = models.ForeignKey(Good)
  38. class Service(AbstractItem):
  39. """ A service we sell
  40. (considered monthly)
  41. """
  42. costs = models.ManyToManyField(
  43. Cost,
  44. through=CostUse,
  45. related_name='using_services')
  46. goods = models.ManyToManyField(
  47. Good,
  48. through=GoodUse,
  49. related_name='using_services')
  50. # services = models.ManyToMany('Service') #TODO