【问题标题】:multiplication in django in djangodjango中的乘法
【发布时间】:2021-12-30 09:24:18
【问题描述】:

我如何在预算模型中将两个数字相乘,例如,我想将工时和每小时费率相乘...然后将该数字添加到所有项目的总成本中...请帮助

from django.db import models
from django.contrib.auth.models import User
from .directors import Directors

class ApprovedBudget(models.Model):
  job=models.CharField(max_length=255)
  time=models.DateTimeField()
  labourhours=models.IntegerField()
  rate=models.DecimalField(max_digits=9, decimal_places=2)
  materials=models.DecimalField(max_digits=9, decimal_places=2)
  travel=models.DecimalField(max_digits=9, decimal_places=2)
  other=models.DecimalField(max_digits=9, decimal_places=2)
  notes=models.CharField(max_length=450)
  budget=models.DecimalField(max_digits=9, decimal_places=2)
  actual=models.DecimalField(max_digits=9, decimal_places=2)
  undercover=models.DecimalField(max_digits=9, decimal_places=2)
  status = models.CharField(max_length=12,default='pending')
  #pending,approved,rejected,cancelled 
  is_approved = models.BooleanField(default=False)
  #hide
  updated = models.DateTimeField(auto_now=True, auto_now_add=False) created = models.DateTimeField(auto_now=False, auto_now_add=True)
  
  objects = Directors()

  class Meta:
    verbose_name = (ApprovedBudget)
    verbose_name_plural = ('ApprovedBudget')
  
  def __str__(self):
    return str(self.job)
  
  @property
  def labour(self):
    if(self.labourhours != None ):
      labour=self.labourhours*self.rate
      return labour

【问题讨论】:

  • 提供的代码看起来正确是什么问题
  • 我没有在管理员中看到显示工时乘以费率的计算结果的变化,当我尝试在过滤器中添加劳动力时,它说它不可调用
  • 你好@TamieClayton 检查我的答案,如果有错误请告诉我。

标签: django activerecord-calculations


【解决方案1】:

您可以通过覆盖模型的save() 方法来做到这一点。
首先在模型中添加一个额外的字段来存储这样的乘法值

class ApprovedBudget(models.Model):
    .....all other fields
    labour = models.IntegerField(blank=True)#set blank=True so it will not raise any validation error while creating object

    def save(self, *args, **kwargs):
        if(self.labourhours != None ):
        self.labour=self.labourhours*self.rate
        super(ApprovedBudget, self).save(*args, **kwargs)

如果您不想将其存储在数据库中而只想在管理界面上显示而不是这样

from django.contrib import admin

class ApprovedBudgetAdmin(admin.ModelAdmin):
      list_display = [..all your fields, 'labour_cost']
      
      def labour_cost(self, obj):
          if obj.labourhours and obj.rate:
             return self.labourhours*self.rate
          return 'None'

【讨论】:

  • 让我试试谢谢
  • 感谢 Ankit 它能够在标题“保存”下创建一个过滤器,但它不会计算工时乘以费率
  • 它产生一个空值
  • 您好@TamieClayton 您想将乘积值存储在数据库中还是只想显示它?
  • 我想把它存入数据库
猜你喜欢
  • 2012-05-25
  • 1970-01-01
  • 2019-01-06
  • 2013-11-04
  • 2011-11-05
  • 2021-12-28
  • 2021-05-26
  • 2015-05-24
  • 1970-01-01
相关资源
最近更新 更多