Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A signal m2m_changed and bug with post_remove

I need to detect a post_remove signal, so I have written :

def handler1(sender, instance, action, reverse, model, pk_set, **kwargs):
if (action == 'post_remove'):
    test1()  # not declared but make a bug if it works, to detect :)

m2m_changed.connect(handler1, sender=Course.subscribed.through)

If I change 'post_remove' by 'post_add' it is ok.. Is it a django's bug about post_remove ??

I use that model and I switch beetween two values of 'subscribed' (so one added and one deleted)

class Course(models.Model):
    name = models.CharField(max_length=30)
    subscribed = models.ManyToManyField(User, related_name='course_list', blank=True, null=True, limit_choices_to={'userprofile__status': 'student'})

I have seen a post with a bug of django, maybe it havn't been fixed... (or it's me ^^)

like image 402
nlassaux Avatar asked Jul 27 '12 10:07

nlassaux


1 Answers

As I understand it, it's not a bug, it's just that Django does not update m2m relations in the way you expect. It does not remove the relations to be deleted then add the new ones. Instead, it clears all of the m2m relations, then adds them again.

There's a related question Django signal m2m_changed not triggered which links to ticket 13087.

So you can check for the pre_clear or post_clear action with the m2m_changed signal, but since those actions do not provide pk_set, it doesn't help you find the related entries before the save, as you wanted to do in your other question.

like image 137
Alasdair Avatar answered Oct 19 '22 19:10

Alasdair