首页 > 解决方案 > 使用外键的属性作为模型中的字段

问题描述

假设我将这些作为代码

class Transaction(models.Model):
    item = models.ForeignKey(Item,on_delete=models.PROTECT)
    total_transaction = get_price()
    coupon = models.ForeignKey(Coupon,on_delete=models.PROTECT)

    def get_price(self):
        return self.item.price * self.coupon.percentage // 100

我想使用优惠券的百分比和项目的价格输入total_transaction,但我似乎无法传递该函数,因为它说“需要”自我?我该如何解决这个问题?

标签: pythondjangodatabase

解决方案


您需要声明total_transaction为属性:

class Transaction(models.Model):
    item = models.ForeignKey(Item,on_delete=models.PROTECT)
    coupon = models.ForeignKey(Coupon,on_delete=models.PROTECT)

    @property
    def total_transaction(self):
        return self.item.price * self.coupon.percentage // 100

注意:属性不会保存到数据库


推荐阅读