我有以下两种型号:
class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ...
我希望活动模型在保存与插入或更新相关的取消时都要注意.
最好的方法是什么?
您想要了解的是Django的信号(也请查看此页面),特别是模型信号 - 更具体地说,是post_save信号.信号是Django的插件/钩子系统版本.每次保存模型时都会发送post_save信号,无论是更新还是创建(并且它会让您知道它是否已创建).这是您在活动取消时使用信号获取通知的方式
from django.db.models.signals import post_save class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) @classmethod def cancellation_occurred (sender, instance, created, raw): # grab the current instance of Activity self = instance.activity_set.all()[0] # do something ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... post_save.connect(Activity.cancellation_occurred, sender=Cancellation)