如何在更新另一个模型字段后用 Django 信号填充模型字段?

How to populate a model field with a Django signal after updating another model field?

我有一个由管理员创建的任务列表,由于任务开始日期由各个代理设置,我想使用信号将任务分配给该代理。

Models.py

class Task(models.Model):
    name = models.CharField(max_length=20, blank=True, null=True)
    agent = models.ForeignKey("Agent", on_delete=models.SET_NULL, null=True)
    start_date = models.DateField(null=True, blank=True)
    notes = models.TextField(default=0, null=True, blank=True)

您可以使用 pre_save 信号来比较旧字段值与新字段值,例如:

@receiver(pre_save, sender=Task)
def assign_task(sender, instance, **kwargs):
    
    # get the task before the new value is saved:
    instance_with_old_value = Task.objects.get(id=instance.id)
    old_start_date = instance_with_old_value.start_date

    # get the task after the new value is saved:
    instance_with_new_value = instance
    new_start_date = instance_with_new_value.start_date

    # do something with dates, assign agent:
    ...