Brian Pace
Brian Pace

Reputation: 39

Refresh a field from another table [Django]

I have these two models:

class probe(models.Model):

    serial=models.CharField("Serial Number",max_length=30,primary_key=True)
    clientID=models.ForeignKey(organisation)
    inst_date=models.DateField("Installation Date")
    exp_date=models.DateField("Expiration Date",blank=True)


    def save(self):
         if self.exp_date is None:
            self.exp_date=self.inst_date.replace(year=self.inst_date.year+1)
    super(probe,self).save()


    def isExpired(self):
        return self.exp_date<=datetime.date.today()
     isExpired.admin_order_field="exp_date"
     isExpired.boolean=True
     isExpired.short_description="Needs calibration"


     def __str__(self):              
         return self.serial

class calibration(models.Model):
    probe=models.ForeignKey(probe)
    date=models.DateField("Date of Calibration")
    isSent=models.BooleanField("Email sent?",default=False)

    def __str__(self):              
        return str(self.date)

    def save(self):
        self.probe.exp_date=self.date.replace(year=self.date.year+1)
        super(calibration, self).save()   

When I create a calibration, I want the expiry date of the probe to update, how can I implement my models to allow that?

Upvotes: 1

Views: 36

Answers (1)

Geo Jacob
Geo Jacob

Reputation: 6009

Try this:

from dateutil.relativedelta import relativedelta

def save(self):
    self.probe.exp_date=self.date + relativedelta(years=1)
    self.probe.save()
    super(calibration, self).save()   

Upvotes: 1

Related Questions