1

I cannot wrap my head around why I'm getting an error here - when the update query is run with this django ORM save() code, I get a UNIQUE Constraint Error:

django.db.utils.IntegrityError: UNIQUE constraint failed: tasks_recurringtask.id

From my understanding, update is executed immediately and only called on the same scheduler job that has the ID referencing the given RecurringTask. Maybe I'm missing something or there is a safe way to do this? Any explanations would be helpful, thanks!

class RecurringTask(models.Model):
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='tasks')
    start_time = models.DateTimeField(default=now)
    scheduler_job = models.OneToOneField(
        Schedule,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        default=None
    )

    def save(self, *args, **kwargs):
        # set all other dependencies for Task
        # update Scheduler Job
        if self.scheduler_job is None:
            self.scheduler_job = Schedule.objects.create(func='tasks.jobs.do_task',
                                                         args=f'{self.pk}',
                                                         next_run=self.start_time
                                                         )
        else:
            Schedule.objects.filter(id=self.scheduler_job_id).update(
                next_run=self.start_time
            )
        super(RecurringTask, self).save(self)
Borzi
  • 537
  • 1
  • 5
  • 21

0 Answers0