通过管理面板更新数据库时调用的方法

时间:2018-02-14 14:17:33

标签: python django wagtail

我的想法是,我不需要每次输入一些数据,其值取决于其他数据的值。例如。

class Example(models.Model):
    1_score_team_1 = models.IntegerField()
    2_score_team_1 = models.IntegerField()
    1_score_team_2 = models.IntegerField()
    2_score_team_2 = models.IntegerField()
    total_score_of_team_1 = models.IntegerField()
    total_score_of_team_2 = models.IntegerField()
    def function:
        total_score_of_team_1 = 1_score_team_1 + 2_score_team_1
        total_score_of_team_2 = 1_score_team_2 + 2_score_team_2
    return update total score of two teams

每次通过管理面板输入数据时都应调用此方法。

1 个答案:

答案 0 :(得分:1)

感谢@ daniel-roseman的链接 我意识到这一点。

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender='app_name.Example')
def my_callback(sender, instance, *args, **kwargs):
   instance.total_score_of_team_1 = instance.1_score_team_1 + instance.2_score_team_1
   instance.total_score_of_team_2 = instance.1_score_team_2 + instance.2_score_team_2