And*_*dré 2 django django-models
我有两个型号.一个名为MainModel,另一个名为HistoricMainModel.每次将数据插入MainModel时,我都希望在HistoricMainModel中自动插入一行.在Django中这样做的最佳/正确方法是什么?
最好的祝福,
如果你已经有了一些自定义save().魔法事情我会建议使用一个post_save()信号或者pre_save()其不断将工作最适合你.
在你的 models.py
@receiver(pre_save, sender=MainModel)
def save_a_historicmodel(sender, **kwargs):
#do your save historicmodel logic here
Run Code Online (Sandbox Code Playgroud)
要么
def save_a_historicmodel(sender, instance, created, **kwargs):
print "Post save was triggered! Instance:", instance
signals.post_save.connect(save_a_historicmodel, sender=MainModel)
Run Code Online (Sandbox Code Playgroud)
这样可以保证每次MainModel保存时都会触发此信号.
| 归档时间: |
|
| 查看次数: |
2064 次 |
| 最近记录: |