[Answered ]-Why does Django ORM not find related object in post_delete signal?

1👍

I believe the sequence of events here is something like this:

  • PumpLog object gets deleted from the Database.
  • Invoice object gets deleted from the Database.
  • In post_invoice_delete, you have access to the Invoice instance. However, there is no way to access the PumpLog instance/database record, as it could only have been accessed inside a PumpLog post_delete hook receiver.

So, when you try to access instance.pump_log, you get a DoesNotExist exception because, simply, the PumpLog object does not exist in the database, or anywhere, anymore.
I believe that the line just returns None rather than raising a DoesNotExist exception.

    PumpLog.objects.filter(index = instance.pump_log_id)

It should only raise an exception if you use get() in place of filter().

As to why you can still access instance.pump_log__id, I believe that it’s simply because the ID of the pump_log is accessible by the Invoice instance itself as a result of the ForeignKey column that probably exists in the database and, thus, translating into an attribute on the object itself, making it unnecessary for the ORM to access the database. Only when you do something that needs to read the PumpLog object from the data do you get the error.

If you indeed do need access to the PumpLog instance, perhaps you should do what you need to do in a post_log_post_delete receiver, which should be able to access the Invoice instance since that would probably still exist.

Leave a comment