Search code examples
djangodjango-signals

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


I have a list of tasks that are created by the admin and as the task start dates are set by individual agents, I would like to use a signal to assign the tasks to that agent.

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)

Solution

  • You can use the pre_save signal to compare the old field value vs. the new field value, something like:

    @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:
        ...