Last active
September 29, 2016 10:04
-
-
Save Diegow3b/3cb7c5a710c5a5c32221def618b28314 to your computer and use it in GitHub Desktop.
Turning arround m2m_changed bug in admin from Django 1.8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Obs1: m2m_changed never trigger the remove signal (pre_remove, post_remove) when deleted, so this ways you can force he do it | |
obs2: Since the pre_clear data will be removed anyways to new valuei n post_add add it again and when you fully remove data | |
the add events wont be trigger, so this solution will simule the exacly action the m2m_changed should do | |
''' | |
class OtherModel(model.Models) | |
pass | |
class MyModel(model.Models): | |
m2m_attribute = models.ManyToManyField(OtherModel,related_name='other_model', blank=True) | |
# SIGNALS | |
from django.db.models.signals import m2m_changed | |
from django.dispatch import receiver | |
@receiver(m2m_changed, sender=MyModel.m2m_attribute.through) | |
def mymodel_m2m_attribute_changed(sender, **kwargs): | |
action = kwargs.pop('action', None) | |
pk_set = kwargs.pop('pk_set', None) | |
instance = kwargs.pop('instance', None) | |
if action == "pre_clear": | |
#Here we do the trick | |
instance_m2m_attributes = instance.m2m_attribute.all() | |
if instance_m2m_attributes: | |
for one_m2m in instance_m2m_attributes: | |
instance.m2m_attribute.remove(one_m2m) | |
instance.save() | |
if action == "post_add" and pk_set: | |
#Do Your Stuff |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment