【问题标题】:Django-tables2 model-based table - custom columns with calculationsDjango-tables2 基于模型的表 - 带有计算的自定义列
【发布时间】:2016-05-14 04:29:22
【问题描述】:

我有一个带有各种属性的模型,其中最复杂的是查找项目的工作小时数,乘以员工的小时费率,然后返回总成本。

类 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,因为我不确定它是否适合我的需求?

谢谢

【问题讨论】:

    标签: python django properties django-tables2


    【解决方案1】:

    您可以使用 Django 的 cached_property 装饰器,然后每个实例的值只会计算一次。

    from django.utils.functional import cached_property
    
    class DesignDetails(models.Model):
    
        @cached_propery
            def actual_cost(self):
                ...
    

    我认为在模型上使用(缓存)属性是一种不错的方法。我不建议将逻辑移到 Django 表 2 中。如果代码在模型上,将更容易重用。

    【讨论】:

    • 这确实有助于加快速度,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多