Get the current and newly added m2m relation in a django model

15 views Asked by At

I am using a manytomany relation on a model, while add(), I want to get the old and new instance of the relation. For that I am using pre_add and post_add m2m_changed signals. During post_add the value of the old instance is already modified to the saved instance. How do I store both of these instances.

The code I am using right now.

`class A:

    m2m = models.ManyToManyField(B, blank=True, related_name="m2m")

    def save_m2m(self, *args, **kwargs):
        action = kwargs.get("action", None)
        initial_instance = None
        if action == "pre_add":
            initial_instance = kwargs.get("instance")
        if action == "post_add":
            instance = kwargs.get("instance")
            # Operation involving initial_instance and instance

    def __init__(self, *args, **kwargs):
        super(A, self).__init__(*args, **kwargs)
        m2m_changed.connect(self.save_m2m, A.m2m.through)`
0

There are 0 answers