我有一个Django模型命名为EmailSendingTask
。这是整个模型-
class EmailSendingTask(models.Model):
order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='order')
status = EnumChoiceField(SetupStatus, default=SetupStatus.active)
time_interval = EnumChoiceField(TimeInterval, default=TimeInterval.five_mins)
immediate_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='immediate_email')
scheduled_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='scheduled_email')
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'EmailSendingTask'
verbose_name_plural = 'EmailSendingTasks'
def __str__(self) -> str:
return f'EmailSendingTask: Order = {self.order}'
immediate_email
和scheduled_email
字段负责保存两个PeriodicTask对象。
我创建了一个名为disable_scheduled_email
的函数,它负责禁用scheduled_email
的周期性任务。函数的详细信息在这里-
def disable_scheduled_email(self):
print(f'Disabling scheduled email...')
self.scheduled_email.enabled = False
self.save(update_fields=['scheduled_email'])
现在,每当我调用这个函数并打印self.scheduled_email.enabled
的值时,我发现它是False
。但是,当我试图查看Django Admin站点时,周期性任务的enabled
值仍然是True
。为什么会发生这种情况?
经过一些实验进入Django Shell我发现,我没有专门调用save()
到外键(scheduled_email
)。我刚刚将self.scheduled_email.save()
添加到disable_scheduled_email
函数中。因此,整个函数变成了:
def disable_scheduled_email(self):
print(f'Disabling scheduled email...')
self.scheduled_email.enabled = False
# self.save(update_fields=['scheduled_email'])
self.scheduled_email.save() #instead of self.save(...), wrote this