我想在更新项目的外键对象(货币)时更新我的对象的最低和最高价格。在这种情况下,它会在每次刷新页面后更新。
my views.py
for item in object_list:
if item.currency.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()
答案 0 :(得分:0)
您可以使用信号来解决此问题: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()
您可能需要进行一些小的调整,但这是一般的想法。在你的情况下,pre_save可能更好,而不是post_save。