Calculating a date within the Model Django timedelta

0

I'm declaring a function (data_prox_prog) to calculate a future date and store in the model, but it's not happening as expected. Here is the code:

class ProgressaoDocente(models.Model):
servidor = models.ForeignKey(Servidor, on_delete=models.PROTECT)
tipo_progressao = models.CharField(choices=const.TIPO_PROGRESSAO_DOC, max_length=1)
classe = models.CharField(choices=const.CLASSE_DOCENTE, max_length=1)
nivel = models.CharField(choices=const.NIVEL_DOCENTE, max_length=1)
data_progressao = models.DateField()
portaria = models.OneToOneField(Portaria, on_delete=models.CASCADE)
data_prox_progressao = models.DateField(blank=True, null=True)

class Meta:
    verbose_name_plural = 'Progressão Docente'

def data_prox_prog(self):
    self.data_prox_prog = (self.data_progressao + timedelta(year=2))
    self.save()

def __str__(self):
    return "{} {}, {}/{}".format(self.servidor, self.tipo_progressao, self.classe, self.nivel)
    
asked by anonymous 02.09.2018 / 04:56

1 answer

1

I was able to resolve using Django Signals pre-save. What is expected is that when you instantiate a new 'ProgressionDocente', from the 'data_progressao', if you define the value of the 'data_prox_progressao', counting another 2 years of the 'data_progressao', follows solution:

class ProgressaoDocente(models.Model):
    servidor = models.ForeignKey(Servidor, on_delete=models.PROTECT)
    tipo_progressao = models.CharField(choices=const.TIPO_PROGRESSAO_DOC, 
    max_length=1)
    classe = models.CharField(choices=const.CLASSE_DOCENTE, max_length=1)
    nivel = models.CharField(choices=const.NIVEL_DOCENTE, max_length=1)
    data_progressao = models.DateField()
    portaria = models.OneToOneField(Portaria, on_delete=models.CASCADE)
    data_prox_progressao = models.DateField(blank=True, null=True)


    class Meta:
        verbose_name_plural = 'Progressão Docente'

    def __str__(self):
        return "{} {}, {}/{}".format(self.servidor, self.tipo_progressao, 
        self.classe, self.nivel)

@receiver(pre_save, sender=ProgressaoDocente)
def callback_progressao_docente(sender, instance, *args, **kwargs):
    instance.data_prox_progressao = (instance.data_progressao + 
    relativedelta(years=+2))
    
02.09.2018 / 15:39