[英]Django-tables2 model-based table - custom columns with calculations
我有一個具有各種屬性的模型,其中最復雜的一種是查找項目的工作小時數,再乘以員工的小時率,然后返回成本的總和。
類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,因為我不確定它是否適合我的需求?
謝謝
您可以使用Django的cached_property
裝飾器,然后對於每個實例僅計算一次該值。
from django.utils.functional import cached_property
class DesignDetails(models.Model):
@cached_propery
def actual_cost(self):
...
我認為在模型上使用(緩存的)屬性是一種好的方法。 我不建議將邏輯移到Django表2中。如果代碼在模型中,則重用代碼會更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.