calculate the warranty duration from the dates provided
This commit is contained in:
parent
8dc93dd398
commit
da1375a030
|
@ -0,0 +1,21 @@
|
|||
def td_format(td_object):
|
||||
"""A helper function to convert time deltas to a human readable format.
|
||||
Taken from here."""
|
||||
seconds = int(td_object.total_seconds())
|
||||
periods = [
|
||||
('year', 60*60*24*365),
|
||||
('month', 60*60*24*30),
|
||||
('day', 60*60*24),
|
||||
('hour', 60*60),
|
||||
('minute', 60),
|
||||
('second', 1)
|
||||
]
|
||||
|
||||
strings = []
|
||||
for period_name, period_seconds in periods:
|
||||
if seconds >= period_seconds:
|
||||
period_value, seconds = divmod(seconds, period_seconds)
|
||||
has_s = 's' if period_value > 1 else ''
|
||||
strings.append("%s %s%s" % (period_value, period_name, has_s))
|
||||
|
||||
return ", ".join(strings)
|
|
@ -1,6 +1,7 @@
|
|||
from django.db import models
|
||||
|
||||
from core.models import Category
|
||||
from core.utils import td_format
|
||||
|
||||
from .device import Device
|
||||
|
||||
|
@ -16,7 +17,6 @@ class Warranty(models.Model):
|
|||
device = models.ForeignKey(Device, on_delete=models.CASCADE)
|
||||
valid_from = models.DateField()
|
||||
valid_until = models.DateField()
|
||||
duration_in_years = models.IntegerField()
|
||||
warranty_type = models.ForeignKey(WarrantyType, models.SET_NULL,
|
||||
blank=True, null=True)
|
||||
|
||||
|
@ -29,3 +29,9 @@ class Warranty(models.Model):
|
|||
@property
|
||||
def customer(self):
|
||||
return self.device.customer
|
||||
|
||||
@property
|
||||
def duration_in_years(self):
|
||||
|
||||
delta = self.valid_until - self.valid_from
|
||||
return td_format(delta)
|
||||
|
|
Loading…
Reference in New Issue