2017-09-02 37 views
-1
I have two models: 
class RateCard(models.Model): 
    name = models.CharField() 
    pricing_type = models.ForeignKey(PriceAttribute) 

and 

class RateCardHistory(models.Model): 
    name = models.CharField() 
    pricing_type = models.ForeignKey(PriceAttribute) 

我想是在RateCard每一個操作的新紀錄應該得到插入RateCardHistory什麼是插入日誌/歷史記錄表中的記錄在Django的最佳方法

哪一個最好的方式實現這一目標Django發出post_save或超過RateCard保存方法的信號,或者是否有任何其他方法會很好。

+0

獲得歷史使用保存方法更明確,更容易理解添加創建日期時間。如果你沒有充分的理由使用信號,最好保持簡單。 –

+0

謝謝@HåkenLid如果您分享任何鏈接/參考將對我非常有用 – Brijesh

+0

如何在RateCard保存方法中啓動或調用RateCardHistory模型以在RateCardHistory中傳遞RateCard值 – Brijesh

回答

0

可以ovveride保存方法RateCard

class RateCard(models.Model): 
    name = models.CharField() 
    pricing_type = models.ForeignKey(PriceAttribute) 

    def save(self, *args, **kwargs): 
     # the call to the super save the record as usual 
     super(RateCard,self).save(*args,**kwargs) 
     # do here what you want... create your new related records 
     new_card_history = RateCardHistory.objects.create(name='the name', pricing_type=self) 

我建議你做一些改變,你的代碼。如果你想通過創作來獲得字段順序,還可以添加相關的名字從RateCard

class RateCardHistory(models.Model): 
    name = models.CharField() 
    created = models.DateTimeField(auto_now_add=True) 
    pricing_type = models.ForeignKey(PriceAttribute, related_name='histories') 
+0

謝謝@karim,我這樣做,我啓動RateCardHistory並傳遞字段值作爲字典new_card_history = RateCardHistory(** data_dict),但事情是它得不到保存..我試着new_card_history.save() – Brijesh

相關問題