9

I'm trying to perform a basic date calculation in a save model in django, see below code:

  class Purchase(models.Model):
    purchase_date = models.DateField()
    purchase_place = models.CharField(verbose_name='Place of Purchase', max_length=255)
    purchaseCategory = models.ForeignKey(PurchaseCategory, verbose_name='Purchase Category')
    cost = models.DecimalField(max_digits=11, decimal_places=2)
    warranty_period_number = models.IntegerField()
    warranty_period_type = models.CharField(max_length=255, choices=(('m', 'Month(s)'), ('y', 'Year(s)')))
    warranty_end_date = models.DateField(editable=False)
    scan = models.CharField(max_length=255)
    alerts = models.BooleanField(verbose_name='Receive Email Alerts?')
    user = models.ForeignKey('auth.User', editable=False)
    created = models.DateTimeField(editable=False, auto_now_add=True)
    modified = models.DateTimeField(editable=False, auto_now=True)

    #custom save model
    def save(self, *args, **kwargs):
        #figure out warranty end date
        if self.warranty_period_type == 'm':
            self.warranty_end_date = self.purchase_date + self.purchase_date.timedelta(months=self.warranty_period_number)
        else:
            self.warranty_end_date = self.purchase_date + self.purchase_date.timedelta(years=self.warranty_period_number)
        super(Purchase, self).save()

I thought the following would work but no luck.. it errors with:

'datetime.date' object has no attribute 'timedelta'

Can anyone point in the right direction to do what I'm trying to do?

Cheers, Ben

Ben Kilah
  • 3,445
  • 9
  • 44
  • 56

1 Answers1

18

timedelta doesnot accept years, so

from datetime import timedelta
# custom save model
def save(self, *args, **kwargs):
    # figure out warranty end date
    if self.warranty_period_type == 'm':
        self.warranty_end_date = self.purchase_date + timedelta(days=self.warranty_period_number*31)
    else:
        self.warranty_end_date = self.purchase_date + timedelta(days=self.warranty_period_number*365.2425)
    super(Purchase, self).save(*args, **kwargs)

Refs Python timedelta in years

Community
  • 1
  • 1
okm
  • 23,575
  • 5
  • 83
  • 90
  • any idea why I would get this error: numeric field overflow DETAIL: A field with precision 11, scale 11 must round to an absolute value less than 1. – Ben Kilah Mar 31 '12 at 08:08
  • @BenKilah A numeric field w/ precision 11 and scale 11 should be less than 1, check [PostgreSQL doc the principle of which applies to other DBs also](http://www.postgresql.org/docs/8.3/static/datatype-numeric.html#DATATYPE-NUMERIC-DECIMAL) – okm Mar 31 '12 at 08:55