是否有可能设置模型字段以从多个表中减去值的总和

时间:2019-04-24 13:38:19

标签: python django database

我正在创建一个加密货币应用程序。我有一个名为“交易”的表,该表可以在“销售表”上存储0或许多销售记录。是否可以在交易模型“ coins_remaining”上设置一个等于(销售表中的金额-sum(amount_sold))的字段。

下面的交易模型

class Transaction(models.Model):
    currency = models.CharField(max_length=20)
    amount = models.IntegerField()
    total_price = models.DecimalField(max_digits=8, decimal_places=2)
    date_purchased = models.DateTimeField()
    note = models.TextField(default="")
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False)

    def save(self, *args, **kwargs):
        self.amount_per_coin = self.total_price / self.amount
        super(Transaction, self).save(*args, **kwargs)


下面的销售表


class Sale(models.Model):
    amount_sold = models.IntegerField()
    total_price_sold = models.DecimalField(max_digits=8, decimal_places=2)
    date_sold = models.DateTimeField(default=timezone.now)
    note = models.TextField(default="")
    transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
    amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False)

    def save(self, *args, **kwargs):
        self.amount_per_coin_sold = self.total_price_sold / self.amount_sold
        super(Sale, self).save(*args, **kwargs)

2 个答案:

答案 0 :(得分:0)

您可以将交易表创建为DataFrame,将“ amount_sold”列的总和减去金额

t = Transaction()
s = Sale()

s.transactions = pd.DataFrame({'id': [1,2,3,4,5], 'amount_sold': [10, 20, 30, 40, 50]})

coins_remaining = t.amount - s.transactions['amount_sold'].sum()

答案 1 :(得分:0)

您可以在执行此操作的交易中定义一个属性:

@property
def coins_remaining(self):
    return self.amount - sum(self.sales.all().values_list('amount_sold', flat=True))