Django 保存方法未按预期工作

Django save method is not working as expected

我覆盖了 Django 保存方法。在保存新的折扣项目时,将执行打印语句,但不会调用 update_discount 方法。我正在使用管理面板来保存折扣商品。我也想在 Django 更新方法上调用相同的 update_discount 方法。

代码:

class Discount(models.Model):
    start_date = models.DateField(default=now)
    end_date = models.DateField()
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    disc_per = models.PositiveIntegerField(default=None)

    class Meta:
        unique_together = ('start_date', 'end_date', 'product')

    def __str__(self):
        return str(self.start_date) + '-' + str(self.end_date) + '-' + str(self.product)

    def save(self, *args, **kwargs):
        print('saved.')
        Discount.update_discount()
        print('updated discount.')
        super().save(*args, **kwargs)

    @staticmethod
    def update_discount():
        discounts = Discount.get_all_discounts()
        products = Product.get_all_products()
        today = date.today()

        # Reset discounted prices of all products
        products.update(disc_price=None)

        # Apply discount on products if today is sale
        for discount in discounts:
            product = Product.get_product_by_id(discount.product.id)

            if (today >= discount.start_date) and (today <= discount.end_date):
                per = discount.disc_per
                price = discount.product.price

                disc_price = Discount.cal_disc_price(per, price)
                product.update(disc_price=disc_price)
            else:
                product.update(disc_price=None)

输出:

saved.
updated discount.

我不确定你为什么知道 update_discount 方法没有被调用。但是你应该尝试像这样修复它:

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    print('saved.')
    self.update_discount()
    print('updated discount.')