Skip to main content
 首页 » 编程设计

python之检测 Django 模型中的字段变化

2025年02月15日22zhoujg

是否可以检测到 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')) 

问题是,当 my_current_price 发生变化时,我需要随时重新计算欧元和美元价格。

我有两个想法:

  1. Somehow override MoneyField and send signal when the field is changed.

  2. Override save method and create a new attribute __my_current_price like here - this works but it makes code very unclear for me.

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

请您参考如下方法:

一种方法是创建信号并将 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)