I have two models Image
and Category
related via a m2m relation (defined in Category). Images may be under several categories. The API allows to remove an image from a category. In response to that I need to remove the image when it has no categories.
I have the following:
@receiver(m2m_changed, sender=Category.images.through)
def delete_image_if_has_no_categories(sender, instance, action, reverse,
model, pk_set, **kwargs):
# we only watch reverse signal, because in other cases the images are
# being moved or copied, so don't have to be deleted.
if reverse and action == 'post_remove':
if not instance.categories.exists():
instance.delete()
I have placed several debug logs to check the code is being run. And it runs. But the images remain in the DB after the instance.delete()
.
I have the remove_from_category
view inside a transaction.atomic
, but it does not help.
Any ideas?
Update
The view call this method in our Image model:
def remove_from_category(self, category_id):
self.categories.remove(category_id)
The view is called via a REST API like this DELETE /category/<catid>/<image-id>
.
The images
field in the Category
model is defined like this:
class Category(MPTTModel):
images = models.ManyToManyField(
'Image',
related_name='categories',
null=True, blank=True,
)
Would the MPTTModel be the culprit? I'm using django-mptt==0.6.0
.