How to add values from one model and insert the result into another using Django?

Asked

Viewed 64 times

0

I have this model that aims to register the available services and their respective values:

class Servico(models.Model):
    nome = models.CharField('Nome do serviço', max_length=255)
    preco = models.DecimalField('Preço do serviço', decimal_places=2)
    data_cadastro = models.DateTimeField('Data de cadastro',auto_now_add=True)
    
    def __str__(self):
        return self.nome

I created another model called sale, where you can register several services for a single sale. I would like to insert the sum of service prices within valor_total

class Venda(models.Model):
    FORMPAG_CHOICES = (
        ('CC', 'Cartão de Crédito'),
        ('CD', 'Cartão de Crédito'),
        ('D', 'Dinheiro'),
        ('T', 'Transferência (Entre contas/PIX)')
    )

    forma_pag = models.CharField('Forma de pagamento', max_length=2, choices=FORMPAG_CHOICES)
    cliente = models.ForeignKey(Cliente, verbose_name='Cliente', on_delete='models.PROTECT')
    servicos = models.ManyToManyField(Servico, verbose_name='Serviços prestados')
    data_cadastro = models.DateTimeField('Data da venda',auto_now_add=True)
    valor_total = # É aqui onde quero inserir o valor total da venda
  • Model.py registered in the database, what vc qr do is performed via Forms.py and with javascript. Since it’s been a while since you sent this question, update the question with what you’ve achieved so far.

1 answer

0

Maybe create a Property in the Sell model forever calculate this for you. Something like below:

class Venda(models.Model):
  # ...

  @property
  def valor_total():
    servicos = self.servicos.all() # aplicar filtros padroes se precisar
    preco_total = 0.00
    for servico in servicos:
       preco_total += servico.preco
    return preco_total

the @property is practically to be able to call venda.valor_total and no need to call venda.valor_total()

I hope this helps.

  • I just don’t understand how it gets inserted into the bank :/

  • You’d have to enter it into the value of each service. This method there is really just to pick up now to enter would have to save in the prices of each service, which then when you catch already picked up straight.

Browser other questions tagged

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