2016-02-04 41 views
1

我有一个模型,其中最复杂的查找工作小时数乘以员工的小时费率,并返回一个总成本。Django-tables2基于模型的表格 - 自定义列的计算

类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 

我显示此使用Django,tables2。理想情况下,我想计算表中的'即时'cost_difference,并避免重新计算actual_cost,而不是将其作为模型中的属性。

如何设置一列来使用其他列的值?或者,我应该在模型本身上使用除属性之外的其他东西吗?

我还在考虑放弃Django-tables2,因为我不确定它适合我的需求吗?

感谢

回答

0

你可以使用Django的cached_property装饰,然后将该值仅会被每个实例计算。

from django.utils.functional import cached_property 

class DesignDetails(models.Model): 

    @cached_propery 
     def actual_cost(self): 
      ... 

我觉得用模型上的(缓存)性能是一个不错的方法。我不建议将逻辑移入Django表2.如果代码位于模型上,重用代码会更容易。

+0

这确实有助于加速一点点,谢谢! – beckys57