[Fixed]-Django Update object only when foreign key object will change

1👍

You can use signals to solve this: https://docs.djangoproject.com/en/1.10/topics/signals/

from django.db.models.signals import post_save
from django.dispatch import receiver
from . models import Currency

# This gets called immediately after any Currency object is saved
@receiver(post_save, sender=Currency)
def update_min_max(sender, **kwargs):
    currency = kwargs.get('instance')
    item = currency.item_set.get(id=2)
    new_min_price = item.min_price * (dollar_rate.value)
    new_max_price = item.max_price * (dollar_rate.value)
    item.min_price = new_min_price
    item.max_price = new_max_price
    item.save()

You might need to make some minor adjustments but this is the general idea. pre_save could be better in your case rather than post_save.

👤Zailef

Leave a comment