4

I am seeing post_delete fire on a model before the instance is actually deleted from the database, which is contrary to https://docs.djangoproject.com/en/1.6/ref/signals/#post-delete

Note that the object will no longer be in the database, so be very careful what you do with this instance.

If I look in the database, the record remains, if I requery using the ORM, the record is returned, and is equivalent to the instance:

>>> instance.__class__.objects.get(pk=instance.pk) == instance
True

I don't have much relevant code to show, my signal looks like this:

from django.db.models.signals import post_delete, post_save

@receiver(post_delete, sender=UserInvite)
def invite_delete_action(sender, instance, **kwargs):
    raise Exception(instance.__class__.objects.get(pk=instance.pk) == instance)
  • I am deleting this instance directly, it's not a relation of something else that is being deleted
  • My model is pretty normal looking
  • My view is a generic DeleteView
  • I haven't found any transactional decorators anywhere - which was my first thought as to how it might be happening

Any thoughts on where I would start debugging how on earth this happening? Is anyone aware of this as a known bug, I can't find any tickets describing any behaviour like this – also I am sure this works as expected in various other places in my application that are seemingly unaffected.

If I allow the execution to continue the instance does end up deleted... so it's not like it's present because it's failing to delete it (pretty sure post_delete shouldn't fire in that case anyway).

Steve
  • 5,771
  • 4
  • 34
  • 49

1 Answers1

2

I believe what I am seeing is because of Django's default transactional behaviour, where the changes are not committed until the request is complete.

I don't really have a solution – I can't see a way to interrogate the state an instance or record would be in once the transaction is completed (or even a way to have any visibility of the transaction) nor any easy way to prevent this behaviour without significantly altering the way the application runs.

I am opting for ignore the problem for now, and not worrying about the repercussions in my use-case, which in fact, aren't that severe – I do welcome any and all suggestions regarding how to handle this properly however.

I fire a more generic signal for activity logging in my post_delete, and in the listener for that I need to be able to check if the instance is being deleted – otherwise it binds a bad GenericRelation referencing a pk that does not exist, what I intended to do is nullify it if I see the relation is being deleted - but as described, I can't tell at this point, unless I was to pass an extra argument whenever I fire the signal inside the post_delete.

Steve
  • 5,771
  • 4
  • 34
  • 49