I came to a conclusion after a long, long time My problem first: I had some update of one attribute from my model to set it to False when my m2m is empty, and true if it has at least 1 element, so the true thing works, but when I try "pre_remove" or "post_remove" never starts, so after some attempts with some examples of differences, I saw something strange in this "pre_clear", every time I change my m2m, it always has the last values, so I manage to forcibly remove these values from mine of m2m and so he starts pre_remove and post_remove, so it works for me. See below code
So now I can automatically set ativo True or False based on my m2m
class Servico(BaseMixin): descricao = models.CharField(max_length=50) #This inheritance from User of django that has is_active boolean field class UsuarioRM(Usuario): servicos = models.ManyToManyField(Servico,related_name='servicos_usuario', blank=True) # SIGNALS from django.db.models import signals from django.db.models.signals import m2m_changed def usuariorm_servicos_changed(sender, **kwargs): action = kwargs.pop('action', None) pk_set = kwargs.pop('pk_set', None) instance = kwargs.pop('instance', None) if action == "pre_clear": if instance.servicos.all(): servicos = instance.servicos.all() for servico in servicos: instance.servicos.remove(servico) instance.save() else: instance.is_active = False instance.save() if action == "post_add": if pk_set: instance.is_active = True else: instance.is_active = False instance.save() m2m_changed.connect( usuariorm_servicos_changed, sender=UsuarioRM.servicos.through )
source share