0

I have a simple model:

class Atividade(models.Model):
    valor_brl = models.DecimalField(max_digits=14, decimal_places=2)
    dolar_ref = models.DecimalField(max_digits=14, decimal_places=2)
    valor_usd = models.DecimalField(max_digits=14, decimal_places=2)

I create after a method to calculate a new value using the two fields from the model

@property
def valor_usd_novo(self):
    valor_usd_novo = self.valor_brl / self.dolar_ref
    return valor_usd_novo

If I call {{ valor_usd_novo }} I get the result I want.

After this I create the save() method, to save valor_usd_novo result in valor_usd field from the model.

def save(self, *args, **kwargs):
    self.valor_usd = self.valor_usd_novo()
    super(Atividade, self).save(*args, **kwargs)

The point is that when I call valor_usd I got no results and the database do not update with the result from valor_usd_novo method.

What I missing here?

vcruvinelr
  • 126
  • 8

2 Answers2

1

valod_usd_novo is a property, so you need treat it like an attribute, not a method. Hence, drop the call and refer as an attribute:

def save(self, *args, **kwargs):
    self.valor_usd = self.valor_usd_novo  # not self.valod_usd_novo()
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Thanks for you quick answer. I already tried this but got no results too. The field `valor_usd` remains with no values in the DB and if I call `{{ atividade.valor_usd }}` I still got no results. – vcruvinelr Oct 31 '19 at 19:46
  • @ViniciusCruvinel Check if you get the other field values correctly as it gets it's value from `self.valor_brl / self.dolar_ref`. – heemayl Oct 31 '19 at 19:47
  • Yes. When I call `{{ atividade.valor_usd_novo }}` (from `def valor_usd_novo(self):`) in my template I got the right result/value from the division. When I override the save() method and call `{{ atividade.valor_usd }}` I got nothing. – vcruvinelr Oct 31 '19 at 19:53
0

I really appreciate all the help. I found the solution for the problem:

def new_value(self, *args, **kwargs):
    self.valor_usd = self.valor_usd_novo
    super(Atividade, self).save(*args, **kwargs)
    return self.valor_usd

With this code when I call {{atividade.new_value}} in the template I got the new value and the value in self.valor_usd update.

vcruvinelr
  • 126
  • 8