On Delete cascade on OneToOne field with celery task

Hi @KenWhitesell, thank you for your reply.

Blockquote
The issue is that the on_delete functionality does not work with Celery tasks because the relationship needs to be defined on the Celery task model

Currently, if I delete a strategy, the associated Celery task isn’t deleted because the one-to-one relationship is defined in the strategy model, not in the Celery model. As a result, the “on_delete” CASCADE doesn’t apply to the Celery task record.

In my application, I’m not deleting Celery tasks directly, but rather deleting the strategy itself. When I do this, I want all related Celery tasks to be deleted as well—both the one associated with the strategy model and those associated with the trading systems related to that strategy.

Here’s a reference topic discussing this behavior that I found on the forum: Does on_delete=models.CASCADE applies bidirectionally?

To achieve the desired behavior—deleting the Celery task when a strategy is deleted, as well as the Celery tasks related to the trading systems of that strategy—I understand that the one-to-one relationship would need to be defined on the TaskResult model. Unfortunately, I can’t modify the TaskResult model because it’s part of Celery and not under my control.

To work around this limitation, I attempted to create a custom delete method, but it isn’t functioning as expected.

def delete(self, *args, **kwargs):
    # Deletes the Celery task associated with the strategy
    if self.optimization_celery_task:
        self.optimization_celery_task.delete()

    trading_systems = TradingSystem.objects.filter(strategy_id=self)

    for trading_system in trading_systems:
        if trading_system.task_id:
            trading_system.task_id.delete()

    super().delete(*args, **kwargs)

This code successfully deletes the Celery task associated with self.optimization_celery_task, but it doesn’t delete the Celery tasks of the trading systems. This is because trading_systems = TradingSystem.objects.filter(strategy_id=self) returns an empty queryset.

I hope this provides a clearer description of the problem!