Django-q how to delete scheduled tasks from code

Viewed 209

I use django-q to schedule a periodic task associated an entry in my model Repository (code here after). But when I delete a Repository entry, the associated Schedule entry is not deleted, and so the django-q jobs associated is not cancelled. Any idea ?

from django_q.models import Schedule


class Repository(models.Model):
    id = models.AutoField(primary_key=True)
[...]
    scheduled_scan = models.ForeignKey(Schedule, on_delete=models.CASCADE, default=None, blank=True, null=True)

thanks a lot

1 Answers

Yeah, it won't work like that. The 'on_delete' atribute refers to the model being the foreign key. In other words, it says that when the Schedule is deleted than your Repository should be deleted too, not the other way around.

To delete the schedule when a repository is deleted you can override the delete method on the Repository model:

def delete(self, *args, **kwargs):
    # Delete the schedule
    Schedule.objects.get(pk=self.schedule_scan).delete()
    # Delete the repository
    super().delete(*args, **kwargs)

Note: I'm not sure if you can just pass the schedule_scan foreign key to the pk param in Schedule.objects.get(pk=self.schedule_scan) or if you'd have to save the schedule ID manually as an IntegerField on your repository model and query that. I'll have to find that out soon.

Apparently, yes, you can, by using self.schedule_scan_id (Django 3.2 documentation)

Related