为了我的研究项目,我正在尝试从php迁移到django。用户可以创建3个变量,例如最小值,最大值和该值的步长。从中我生成列表,然后我尝试做一些数学运算并将结果呈现为表,但不能低估如何正确执行它。这是我在python上的可怕原型代码:
import numpy as np
mcharge = np.arange(0.01, 0.38, 0.01)
charge = np.arange(20, 57, 1)
mdiscount = np.arange(0.001, 0.013, 0.001)
discount = np.arange(5, 23, 1.5)
clist = charge.tolist()
mlist = mcharge.tolist()
mdlist = mdiscount.tolist()
dlist = discount.tolist()
result_sum_n_m_n = [(x + y) / 100 for x,y in zip(charge, margin)]
result_sum_s_m_s = [(x + y) / 100 for x,y in zip(mdiscount, discount)]
result_sum_a = [ '%.4f' % elem for elem in result_sum_n_m_n ]
result_sum_b = [ '%.4f' % elem for elem in result_sum_s_m_s ]
n_m_n = result_sum_a * 12
n_m_n.sort()
s_m_s = result_sum_b * 37
n_m = [float(i) for i in n_m_n]
s_m = [float(i) for i in s_m_s]
multiply = [(x * y) for x,y in zip(n_m, s_m)]
minus = [(x- y) for x, y in zip(n_m, s_m)]
last_minus = [(x - y) for x, y in zip(minus, multiply)]
con = [(x / y) for x, y in zip(n_m, last_minus)]
print('result {}, len {}'.format(con, len(con)))
结果是创建矩阵12x37,如下所示:
1.4283164995181838, 1.6389078861692066, 1.9223379318295355, 2.3242982675208066, 2.9439896046711893, 4.004603793386458, 6.259777970274032, 14.329202140572251, -49.56638700424323, -9.079561186305252, -4.997501249375312, -3.4475326365561463,
1.4042354198677265, 1.5980294517892306, 1.8538770902420096, 2.2072644412008695, 2.7313961644544786, 3.574587978568797, 5.170847049689823, 9.343061021478366, 48.37766802148688, -15.223037046585988, -6.5767613173797335, -4.194435010402278,
.....
这是我尝试使用它的模型
class Margin(models.Model):
minimal = models.DecimalField()
maximal = models.DecimalField()
step = models.DecimalField()
def gen_range_margin(self):
margin = np.arange(self.minimal, self.maximal, self.step)
return margin
class Charge(models.Model):
minimal = models.DecimalField()
maximal = models.DecimaField()
step = models.DecimaField()
def gen_range_charge(self):
charge = np.arange(self.minimal, self.maximal, self.step)
return charge
.......
.......
class Calculus(models.Model):
product = models.OneToOneField(Product)
margin = models.OneToOneField(Margin)
charge = models.OneToOneField(Charge)
mdiscount = models.OneToOneField(Mdiscount)
discount = models.OneToOneField(Discount)
那么我该如何在模型中放入用于生成矩阵的代码(我知道那是一团糟),以及如何正确执行?可能我需要在应用中创建一些filters
。
答案 0 :(得分:0)
如果您将PostgreSql用作数据库,则可以使用ArrayField,在其中可以在计算后直接存储数组。例如:
class Margin(models.Model):
...
@property
def gen_range_margin(self):
margin = np.arange(self.minimal, self.maximal, self.step)
return margin
class Charge(models.Model):
...
@property
def gen_range_charge(self):
charge = np.arange(self.minimal, self.maximal, self.step)
return charge
from django.contrib.postgres.fields import ArrayField
class Calculus(models.Model):
result = ArrayField(ArrayField(models.DecimalField()))
...
def do_the_math(self):
# your calculation
self.result = result_as_array
def save(self, *args, **kwargs):
self.do_the_math()
return super(Calculus, self).save(*args, **kwargs)