soynatan / django-easy-audit

Yet another Django audit log app, hopefully the simplest one.
GNU General Public License v3.0
735 stars 182 forks source link

Preserve instance.pk in pre_save signal handler #260

Open Alex-Sichkar opened 1 year ago

Alex-Sichkar commented 1 year ago

Hi there! Thanks for a very useful project.

I believe that instance.pk should be preserved in the pre_save signal handler before passing to a transaction.on_commit() callback. There are cases, such as when using transactions, where the instance might not have a primary key already. For instance:

class Parent(models.Model):
    ...

class Child(models.Model):
    parent = models.ForeignKey(Parent, ...)
    ...

    def delete(self):
        super().delete()
        self.parent.foo = 'bar'
        self.parent.save()

@transaction.atomic
def some_function(parent):
    for child in parent.child_set.all():
        ...
        child.delete()
    parent.delete()

The callback runs only after the outermost transaction has been committed, but the parent has already been deleted and does not have a primary key at that moment.