rsinger86/django-lifecycle

AFTER_DELETE hook on ManyToMany relationships

Closed this issue · 1 comments

Hi,
I'm writing this issue because I think the AFTER_DELETE hook does not work as expected on m2m relationships.
If we have something like that:

class Product(LifecycleModel):
	title = models.Charfield(max_length=100)
	images = models.ManyToManyField(
        to="ProductImage", through="ProductImageRelationship", related_name="products"
    )

class ProductImageRelationship(LifecycleModel):
    product = models.ForeignKey("Product", on_delete=models.CASCADE)
    image = models.ForeignKey("ProductImage", on_delete=models.CASCADE)
    order = models.IntegerField(default=0, help_text="Lower number, higher priority")

class ProductImage(LifecycleModel):
	field_name = models.CharField(max_length=40)

If I write a hook on ProductImageRelationship model like this:

    @hook(AFTER_DELETE, on_commit=True)
    def deleting_image(self):
        print("Image deleted...")

the hook is never triggered when I do

p = Product.objects.get(pk=123)
i = p.images.first()
# to remove image from product do
p.images.remove(i)
# or do this
i.products.remove(p)

However, If I add a receiver like this:

@receiver(post_delete, sender=ProductImageRelationship)
def deleting_image(sender, instance, **kwargs):
    print("Image deleted...")

The receiver is triggered as is expected.

I think I'm doing it correctly 😕 but I'm not sure completely.

Refer to issue #120, it is not possible to use Django-lifecycle with a through model for a Many to Many.