[英]Django-tables2 model-based table - custom columns with calculations
I have a model with various properties on, the most complex of which looks up the number of hours worked on a project, multiplies by the employee's hourly rate, and returns a sum total of the cost. 我有一个具有各种属性的模型,其中最复杂的一种是查找项目的工作小时数,再乘以员工的小时率,然后返回成本的总和。
class DesignDetails(models.Model): 类DesignDetails(models.Model):
@property
def allowed_days(self):
return BudgetItem.objects.get(budget__project=self.project, budget__current_marker=1, name=design_time_string).quantity
@property
def actual_cost(self):
total = 0
design_hours = self.project.designhours_set.exclude(hours_2=None)
for hours in design_hours:
dh2 = hours.hours_2
if dh2:
rate = hours.daily_record.employee.hourly_rate
if not rate:
rate = 30
total += (dh2*rate)
return total
@property
def cost_allowed(self):
return self.allowed_days * design_rate * hours_in_day
@property
def cost_difference(self):
return Decimal(self.actual_cost) - self.cost_allowed
I'm displaying this using Django-tables2. 我正在使用Django-tables2显示它。 Ideally I'd like to calculate the cost_difference 'on the fly' in the table, and avoid having to recalculate the actual_cost, rather than having it as a property on the model.
理想情况下,我想在表中“即时”计算cost_difference,而不必重新计算actual_cost,而不是将其作为模型的属性。
How can I set up a column to use the value of other columns? 如何设置一列以使用其他列的值? Alternatively, should I be using something other than a property on the model itself?
另外,我是否应该在模型本身上使用属性以外的其他东西?
I'm also considering abandoning Django-tables2, as I'm not sure it suits my needs here? 我也正在考虑放弃Django-tables2,因为我不确定它是否适合我的需求?
Thanks 谢谢
You could use Django's cached_property
decorator, and then the value will only be calculated once for each instance. 您可以使用Django的
cached_property
装饰器,然后对于每个实例仅计算一次该值。
from django.utils.functional import cached_property
class DesignDetails(models.Model):
@cached_propery
def actual_cost(self):
...
I think that using a (cached) property on the model is an ok approach. 我认为在模型上使用(缓存的)属性是一种好的方法。 I wouldn't recommend moving the logic into Django tables 2. It will be easier to reuse the code if it's on the model.
我不建议将逻辑移到Django表2中。如果代码在模型中,则重用代码会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.