Reputation: 152
So lets say I have to TimeField's in my model. One for start and one for finish. How would I get a total time from that? Basically I have this:
class Job(models.Model):
name = models.CharField(max_length=30)
date = models.DateField()
time_started = models.DateTimeField(blank=True, null=True)
time_finished = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.name
I want to do something like a model method or a view function maybe like this:
def get_total_time(self):
return time_finished - time_started
But this isn't working.
Upvotes: 1
Views: 676
Reputation: 477676
You can add a property that calculates the duration, so the difference between time_finished
and time_started
. However, you should check if both are not None
. If one (or both) are None
, you can for example return None
:
class Job(models.Model):
name = models.CharField(max_length=30)
date = models.DateField()
time_started = models.DateTimeField(blank=True, null=True)
time_finished = models.DateTimeField(blank=True, null=True)
@property
def duration(self):
if self.time_finished is not None and self.time_started is not None:
return self.time_finished - self.time_started
def __str__(self):
return self.name
Upvotes: 2