How to efficiently render calculated fields on a table?

So the “least invasive” / “least disruptive” solution I came up with looks like this:

class Product(models.Model):
    largo = DecimalField
    ancho = DecimalField
    alto = DecimalField
    tiempo = PositiveIntegerField
    
	def precio_costo(self, vars) -> float:
        precioBase = (self.largo / 100) * (self.ancho / 100)

        precioLatCorto = (
            (self.ancho / 100) * (self.alto / 100)
        )

        precioLatLargo = (
            (self.largo / 100) * (self.alto / 100)
        )

        horas: float = self.tiempo / 60

        # Cast to Decimal to be able to multiply it with another Decimal
        precio_tiempo = Decimal(horas) * vars.precio_hora ### Repeated query

        return precioBase + precioLatCorto + precioLatLargo + precio_tiempo

    def precio_venta_crudo(self, vars) -> float:
        """ Calcula el precio de venta al público del producto crudo """

        # Precio costo * % de ganancia
        return self.precio_costo(vars) * (
            (vars.ganancia_por_menor / 100) + 1 ### Repeated query
        )

    def precio_terminado(self, vars) -> float:
        """ Calcula el precio del producto terminado, sin la ganancia """

        tiempo_terminado = (self.tiempo * 2) / 60

        precio_tiempo_terminado = (
            Decimal(tiempo_terminado) * vars.precio_hora ### Repeated query
        )

        return (
            self.precio_costo(vars)
            + vars.precio_pintado
            + precio_tiempo_terminado
        )

    def precio_venta_terminado(self) -> float:
        """ Calcula el precio de venta al público del producto terminado """
		vars = Variable.objects.get(pk=1)
        # Precio terminado * % de ganancia
        return self.precio_terminado(vars) * (
            (vars.ganancia_por_menor / 100) + 1 ### Repeated query
        )

(I tried to maintain the style and structure of what you’ve already done - I mostly wanted just to illustrate what I was talking about in my previous reply.)

This is not a “perfect” solution - there’s no error checking on the get, and there’s no way to call the other functions without passing a variable, or no way to use this without the Variable object being present. Just hoping it gives you some ideas.

Ken

1 Like