Home > other >  Django - update query doesn't work in pre_delete signal
Django - update query doesn't work in pre_delete signal

Time:06-20

I tried to update a Transaction model queryset in the below pre_delete signal that connected to the Wallet model, but it didn't work.

The signal triggers, and all lines work correctly, except the last line :(

@receiver(pre_delete, sender=Wallet)
def delete_wallet(sender, instance, **kwargs):
    if instance.is_default:
        raise ValidationError({"is_default": "You can't delete the default wallet"})

    q = {"company": instance.company} if instance.company else {"user": instance.user}

    try:
        default_wallet = Wallet.objects.get(**q, is_default=True)
    except Wallet.DoesNotExist:
        default_wallet = Wallet.objects.filter(**q).exclude(pk=instance.pk).first()

    if not default_wallet:
        raise ValidationError({"is_default": "You can't delete the last wallet"})

    instance.transactions.all().update(wallet=default_wallet)

CodePudding user response:

Maybe it cant find default wallet so it tries go get the first one which is the wallet you want to delete (because it's before delete so it still exist).

Try to exclude pk=instance.pk in your default_wallet query.

CodePudding user response:

I moved the logic to the delete() function of the Wallet model instead of using the pre_delete() signal, and it's fixed now.

  • Related