Is it possible to detect that field in Django model has been changed?
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'))
The thing is that I need to recalculate EUR and USD price anytime when my_current_price
is changed.
I have two ideas:
Somehow override
MoneyField
and send signal when the field is changed.Override save method and create a new attribute
__my_current_price
like here - this works but it makes code very unclear for me.
EDIT: I store the price in different currencies because of faster database lookups.
To check if a field has changed when saving with Python Django, we can override the `init method of the model class to keep a copt of the original value. to add the __init__ method that sets the __original_name variable to self.name to keep the original name value.
The Django web framework includes a default object-relational mapping layer (ORM) that can be used to interact with application data from various relational databases such as SQLite, PostgreSQL and MySQL. The Django ORM is an implementation of the object-relational mapping (ORM) concept.
This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle. One-to-one relations are defined using OneToOneField field of django.
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db. models. related module but is typically referenced from django.
One way is to create a signal and compare instance
with an object from database. But it seems that better way is to override save
method which is a best practice.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With