【问题标题】:Django save method is not working as expectedDjango保存方法没有按预期工作
【发布时间】:2021-01-21 09:24:14
【问题描述】:

我覆盖了 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.

【问题讨论】:

  • 尝试使用 self. self.update_discount()
  • @c.grey 我之前尝试过 self.update_discount() 。它没有用。
  • 尝试在 update_discount 函数中打印一些东西。
  • 调用了很多静态方法,但实现不共享。很难说哪里出了问题
  • 为什么知道update_discount方法没有被调用?

标签: django django-models django-3.0


【解决方案1】:

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

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

【讨论】:

  • 非常感谢您指出我的愚蠢错误。我不知道我们可以在 super().save(*args, **kwargs) 之后添加代码。
猜你喜欢
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多