![](/img/trans.png)
[英]How can I create an instance of one model as soon as an instance of a different model is created?
[英]How can I make a variable derived from a model class instance change as soon as another instance is created in Django?
在我的models.py中,我有一個模型類ExchangeRate,我最近使用它來派生一個稱為rate的變量。 然后,我聲明了一個使用此變量來生成GBP到歐元的對應值的函數。
我的其中一個視圖使用該函數來更新上下文變量。
這很好用,但是當我創建一個應該成為最新版本的ExchangeRate實例時,我發現即使我留下了感興趣的URL,前一個值仍然存在。 我只能獲得停止和重新啟動開發服務器時要使用的新值。
當我離開然后返回相關的頁面/ URL,或者每次瀏覽器刷新時,如何更改匯率以及創建新的ExchangeRate實例?
我懷疑這與我需要的會話存儲有關(假設這是問題,不要將其關閉)。
以下是更多詳細信息:
* models.py
class ExchangeRate(models.Model):
value = models.DecimalField(max_digits=5, decimal_places=2)
date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return str(self.value)
我像在課下一樣分配它-
rate = ExchangeRate.objects.latest('date').value
並在以下功能中使用了它-
def euro_total(amount):
return int(rate * amount)
* views.py。
輸出用於填充以下SessionWizardView的上下文
class PaymentWizard(SessionWizardView):
def get_context_data(self, form, **kwargs):
context = super(PaymentWizard, self).get_context_data(form=form, **kwargs)
cleaned_data = super(PaymentWizard, self).get_cleaned_data_for_step('amount') or {'method': 'none'}
payment_choice = cleaned_data.get('payment_choice')
if cleaned_data.get('amount'):
amount = int(cleaned_data.get('amount'))
if self.steps.current == 'confirm_amount' or 'bank' or 'card' and not None:
updates =({'input_amount': amount},
{'payment_choice': payment_choice},
{'GBP_total': gbp_total(amount, payment_choice)},
{'EURO_total': euro_total(amount)},
)
for update in updates:
context.update(update)
return context
感謝大家。
因此,您的最終評論已揭示了問題所在。 首次導入模塊時,將執行在全局級別定義的所有操作,並且直到服務器進程重新啟動后才更改。
您需要將該行移動到每次執行的位置:例如,在euro_total
函數內部。
另外,如果您擔心每次都訪問數據庫,則可以使用memcache之類的方法,並且超時時間較短,並讓您的函數在從數據庫加載之前先檢查緩存。
或者,您可以向ExchangeRate添加一個保存后的信號,當將新值添加到數據庫時,該信號顯式設置全局rate
變量。
如果rate
需要是全局級別的項目(也許您將其用作緩存的值?),則如@Daniel所說,只要保存新的ExchangeRate對象,就可以使用后保存信號自動刷新它。
請參閱django.db.models.signals.post_save以及如何使用信號
在Django文檔中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.