检测 Django 模型中的字段变化

Mil*_*ano 7 python django django-models

是否可以检测到 Django 模型中的该字段已更改?

class Product(models.Model):
    my_current_price = MoneyField(max_digits=20, decimal_places=2, null=True, blank=True,
                                  verbose_name=_('My original price'))
    my_eur_price = MoneyField(max_digits=20, decimal_places=2, null=True, blank=True, verbose_name=_('My price in EUR'))
    my_usd_price = MoneyField(max_digits=20, decimal_places=2, null=True, blank=True, verbose_name=_('My price in USD'))
Run Code Online (Sandbox Code Playgroud)

问题是我需要随时重新计算欧元和美元的价格my_current_price

我有两个想法:

  1. MoneyField当字段更改时,以某种方式覆盖并发送信号。

  2. 覆盖 save 方法并创建一个__my_current_price这里这样的新属性- 这有效,但它使代码对我来说非常不清楚。

编辑: 由于更快的数据库查找,我以不同的货币存储价格。

Mil*_*ano 10

一种方法是创建一个信号并instance与数据库中的对象进行比较。但似乎更好的方法是覆盖save方法,这是最佳实践。

def save(self,*args,**kwargs):
    old = Model.objects.filter(pk=getattr(self,pk,None)).first()
    if old:
        if old.attr!=self.attr:
            # attr changed
    super(Model,self).save(*args,**kwargs)
Run Code Online (Sandbox Code Playgroud)

  • QuerySet 是惰性的,将它们用作布尔值将在数据库中执行相应的查询。相反,删除 .first() 并通过执行 old.exists() 检查实例是否存在 (2认同)