是否可以检测到 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 发生变化时,我需要随时重新计算欧元和美元价格。
我有两个想法:
Somehow override
MoneyFieldand send signal when the field is changed.Override save method and create a new attribute
__my_current_pricelike 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)
