Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect field change in Django model

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:

  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.

EDIT: I store the price in different currencies because of faster database lookups.

like image 648
Milano Avatar asked Jul 05 '17 07:07

Milano


People also ask

When saving How can you check if a field has changed Django?

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.

What is Django's ORM?

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.

What is Onetoone field in Django?

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.

What is ForeignKey Django models?

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.


1 Answers

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)
like image 111
Milano Avatar answered Sep 21 '22 11:09

Milano