Detecting modifications in ManyToMany field

1,187 views
Skip to first unread message

Fabien Schwob

unread,
Mar 7, 2015, 5:59:30 AM3/7/15
to django...@googlegroups.com
Hello,

I would like to detect changes in a ManyToMany field, to update data
in the linked Model. I've two objects :

class Category(models.Model):
    .... some fields ...


class Post(models.Model):
    .... some fields ...
    categories = models.ManyToManyField(Category)

And I would like to detect (in the admin and when accessing the object
in python) when categories are added or removed to a Post. To update
some fields in the Category model. But I've tried with :

 * django.db.models.signals.m2m_changed, but it doesn't appear to be
trigged in the admin
 * by overriding Post.save(), but I get the same information before
and after the save() (I think it's because m2m are handled after
save() has finished) :

def save(self, *args, **kwargs):
        print Post.objects.get(pk=self.id).categories.all()
        super(Post, self).save(*args, **kwargs)
        print Post.objects.get(pk=self.id).categories.all()

Any solutions to handle this case ? With a custom signal, or anything else ?

Thanks
-- 
Fabien Schwob

Vijay Khemlani

unread,
Mar 7, 2015, 10:51:57 AM3/7/15
to django...@googlegroups.com
You might find the m2m_changed signal useful


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAL%3DxoZRnd7812MykJSsh3Avhh%2BiFk9J3g9nkhv61UA%3D4a9j8Ow%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Vijay Khemlani

unread,
Mar 7, 2015, 10:54:17 AM3/7/15
to django...@googlegroups.com
You might find the m2m_changed signal useful

On Sat, Mar 7, 2015 at 7:57 AM, Fabien Schwob <xphu...@gmail.com> wrote:

--

Fabien Schwob

unread,
Mar 8, 2015, 7:17:23 PM3/8/15
to django...@googlegroups.com
With the m2m changed signal I can only have the state of the object after it has been saved. Not the difference between before and after the change.

Vijay Khemlani

unread,
Mar 8, 2015, 7:29:39 PM3/8/15
to django...@googlegroups.com
Haven't tested it, but the "pre_add" and "pre_remove" actions in the m2m_changed signal should be triggered before the change, and they include a pk_set arg with the id's of the related M2M model being added / removed.

You could also link to the post_save and post_remove which contain the same flag, but that depends on what are you trying to accomplish.

Reply all
Reply to author
Forward
0 new messages