1

I am trying to get differenc of two Datetiemfield in Djago. I have tried overriding the default save() but still getting error.

models.py

class Sample(models.Model):
    ad_start = models.DateTimeField() 
    ad_end = models.DateTimeField()
    ad_duration = models.IntegerField()

@property
def get_time_diff(self):
    timediff = self.ad_end - self.ad_start
    return timediff
    #return relativedelta(self.ad_end, self.ad_start)

def save(self, *args, **kwargs):
    self.ad_duration = self.get_time_diff()
    super(Sample, self).save(*args, **kwargs)

forms.py

class SampleForm(forms.ModelForm):
class Meta:
    model = Sample
    exclude = ("submitted", 'ad_duration', "list_date" )
    widgets = {
        'ad_start': DatePickerInput(), 
        'ad_end': DatePickerInput(),
    }

Error

Django Version: 2.1.7
Exception Type: TypeError
Exception Value:'datetime.timedelta' object is not callable
ruddra
  • 50,746
  • 7
  • 78
  • 101
Jhon Doe
  • 113
  • 1
  • 11

1 Answers1

2

There are two changes required in your code.

First, you need to remove @property from method get_time_diff. Because you can't call a property method via (). Or, you can still keep the property method ,but don't call it in save function, for example like this: self.ad_duration = self.get_time_diff

Second, you need to update the model field to DurationField to store the time delta object created in get_time_diff. Like this:

class Sample(models.Model):
        ad_start = models.DateTimeField() 
        ad_end = models.DateTimeField()
        ad_duration = models.DurationField()


    def get_time_diff(self):
        timediff = self.ad_end - self.ad_start
        return timediff


    def save(self, *args, **kwargs):
        self.ad_duration = self.get_time_diff()
        super(Sample, self).save(*args, **kwargs)

Or you can get the total seconds from get_time_diff and store it in ad_duration field(which will be a float field).

class Sample(models.Model):
    ad_start = models.DateTimeField() 
    ad_end = models.DateTimeField()
    ad_duration = models.FloatField()

    def get_time_diff(self):
        timediff = self.ad_end - self.ad_start
        return timediff.total_seconds()  # returns value in seconds
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • DurationField() has created bigint(20) type in mysql database. the stored value in database is "86400000000". And in django admin interface the value is shown as "1 00:00:00". How can i show it in admin interface as Day.(e.g. 1, 2 ) – Jhon Doe Mar 05 '19 at 09:47
  • 1
    You can create a [read only method](https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields) in admin site, and show the day following this [answer](https://stackoverflow.com/questions/2119472/convert-a-timedelta-to-days-hours-and-minutes). – ruddra Mar 05 '19 at 09:53