I am generating a model in which I want to save 3 data as percentages to later apply them in some formulas.
Model
class Factura(models.Model):
id = models.BigAutoField(primary_key = True)
perfil = models.ForeignKey(Perfil)
n_factura = models.IntegerField()
fecha_inicio = models.DateField() #fecha en la que empieza la factura
fecha_fin = models.DateField() #fecha en la que termina la factura
comision = models.DecimalField(max_digits=14, decimal_places=2)
iva = models.DecimalField(max_digits=14, decimal_places=2)
total = models.DecimalField(max_digits=14, decimal_places=2)
fecha_creacion = models.DateTimeField(auto_now_add = True)
rte_iva = models.DecimalField(max_digits=14, decimal_places=2, blank=True, null=True)
rte_ica = models.DecimalField(max_digits=14, decimal_places=2)
rte_fte = models.DecimalField(max_digits=14, decimal_places=2)
porcentaje_rte_iva = models.IntegerField(blank=True, null=True)
porcentaje_rte_ica = models.IntegerField()
porcentaje_rte_fte = models.IntegerField()
porcentaje_comision = models.IntegerField()
porcentaje_iva = models.IntegerField()
I want to know if there is any way to save data as percentages and make them numeric or somehow make a formula like:
porcentaje_iva = %15
calculo_iva = total_producto * porcentaje_iva
I leave you here a way to do it, the thing is to put the product as a decimal of 0.15 in case it is 15% and then add
Precio + (Precio * PorcentajeDeIva)
This way you have a way to add a percentage to a price, you can vary it as you want, adding, subtracting. As you see.
Instead, if you want to save
15%
asiva = 15
the thing change to:If it is data that can be calculated with the data you already have, I would recommend not storing it and simply defining a percentage function in the model decorated as a property . The main problem with storing calculated data is that if its parameters are updated, it always has to be recalculated, and if is passed can lead to error