Django:在两个不同模型的不同字段上的操作

时间:2020-08-03 16:47:08

标签: python django model

这里定义了两个类,我想对两个模型的不同字段进行一些计算。

class A(models.Model):
    newspaper = models.CharField(max_length=50)
    language = models.CharField(max_length=50, choices=Language)
    wh_price = models.DecimalField(max_digits=6,decimal_places=2)
    sa_price=models.DecimalField(max_digits=6,decimal_places=2)

class B(models.Model):
    added_date = models.DateField(max_length=32,auto_now_add=True)
    newspaper = models.ForeignKey(Newspaper,on_delete=models.CASCADE)
    qty=models.IntegerField(default=0)
    qty_return =models.IntegerField(default=0)
    total = models.DecimalField(max_digits=6,decimal_places=2)

总计(来自B)= wh_price(来自A)*数量(来自B)

1 个答案:

答案 0 :(得分:0)

您可以按如下方式覆盖类b的保存功能:

class Intake(models.Model):
    # your fields..
    # below is the save function which we are overriding
    save(self, *args, **kwargs):
        self.total = self.newspaper.wh_price * self.qty
        super(Intake, self).save(*args, **kwargs)

据我所知,这将达到目的。

相关问题