I am working on creating a contract model with Django and I came cross on how to get the time duration from the start_date to the end_date??
class Contract(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField(max_length=10)
start_date = models.DateField(auto_now_add=True)
end_date = models.DateField(auto_now_add=True)
duration = models.IntegerField(end_date - start_date) # how get the duration by hours
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
CodePudding user response:
I would advise not to store this in a field: several ORM queries like for example .update(…)
[Django-doc] circumvent the .save(…)
method [Django-doc], so that means that there are ways to update the start_date
, or end_date
without the duration
being updated properly.
You can add a property that will simply determine the duration when necessary, indeed:
from datetime import timedelta
class Contract(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField(max_length=10)
start_date = models.DateField(auto_now_add=True)
end_date = models.DateField(auto_now_add=True)
created_at = models.DateTimeField(auto_now_add=True)
@property
def duration(self):
return (self.end_date - self.start_date) // timedelta(hours=1)
def __str__(self):
return self.name
CodePudding user response:
If you want to calculate a field in your model one good approach is to do that in an overridden save method.
Substracting one datetime from another results in a timedelta object. I am converting this here into seconds, assuming that is what you wanted.
class Contract(models.Model):
...
duration = models.IntegerField()
....
def save(self, *args, **kwargs):
self.duration = (self.end_date - self.start_date).total_seconds()
super().save(*args, **kwargs)