Hello everyone, me again.
I think I have some design problem.
I have a Product model with some properties:
class Product(models.Model):
length = DecimalField
width = DecimalField
height = DecimalField
Also I have a Variable model acts like a singleton,
just one register to store variables used in my system.
# This model isn't related to Product
class Variable(models.Model):
var1 = DecimalField
var2 = DecimalField
var3 = DecimalField
var4 = DecimalField
For each Product, I have 4 model methods to calculate different prices:
- def cost_price = length + width + height + var1
- def sale_price =
cost_price
+ var2 - def finished_price = cost_price + var3
- def sale_finished_price = finished_price * var4
Problem
This are not the exact calculations but you can start to see where the problem is.
Calling sale_finished_price
calls finished_price
which calls cost_price
and so on. Also the vars
count as queries to the DB.
The problem arises when I render a table of Products, with one of the fields being sale_finished_price
.
This shoots a lot of similar queries for making the calculations.
Django Debug Toolbar Information
SELECT "variables_variable"."id",
"variables_variable"."created",
"variables_variable"."modified",
"variables_variable"."is_removed",
"variables_variable"."precio_hora",
"variables_variable"."precio_pintado",
"variables_variable"."ganancia_por_mayor",
"variables_variable"."ganancia_por_menor",
"variables_variable"."ganancia_fibrofacil"
FROM "variables_variable"
WHERE ("variables_variable"."is_removed" = false AND "variables_variable"."id" = 1)
28 similar queries. Duplicated 28 times.
I think I can’t use select_related()
and prefetch_related()
in this case, because there are no relations between Product
and Variable
.
If you read until here, thanks!
Hopefully we’ll find some efficient way to do this.