Calculating a date inside the Model Django timedelta

Asked

Viewed 219 times

0

I am declaring a function (data_prox_prog) to calculate a future date and store in the model, but it is not happening as expected. Follows 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)
  • It will be useful to help if you put details of the error that appears, or the expected result and the current result. The code inside ProgressaoDocente should not be indented?

1 answer

1

I was able to solve it using pre-save Django Signals. What is expected is that when a new 'Teacher Progression', from data_progression, is set the value of 'data_prox_progression', counting 2 more years of 'data_progression', 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))
  • You can also overwrite the method save and do that assignment before saving. Using Signals (such as pre/post save) can generate some inconsistencies in the future (this being cases where the trend of the system is to grow).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.