django instance.add() is not working on new m2m field added

Difference between Code 1 and Code 2 given below is that industry and dindustry fields are interchanged. While Code 1 works fine Code 2 doesn’t update the database. Can someone please help…

Note:

  1. Table was altered and dindustry was newly created.
  2. No migration issues, I am able to add records to both industry and dindustry through django Admin

Code 1:

@receiver(m2m_changed, sender=Company.dindustry.through)
def video_category_changed(sender, instance, action, pk_set, **kwargs):
    if action == "post_add":
        sectors = Sectors.objects.filter(id__in=pk_set)
        roots = set()
        for sector in sectors:
            root = sector.get_root()
            if not instance.industry.filter(id=root.id).exists():
                instance.industry.add(root)
                print('data added')

Code 2:

@receiver(m2m_changed, sender=Company.industry.through)
def video_category_changed(sender, instance, action, pk_set, **kwargs):
    if action == "post_add":
        sectors = Sectors.objects.filter(id__in=pk_set)
        roots = set()
        for sector in sectors:
            root = sector.get_root()
            if not instance.dindustry.filter(id=root.id).exists():
                instance.dindustry.add(root)
                print('data added')

My model is as below:

class Company(MPTTModel):
    industry = models.ManyToManyField(Sectors, related_name='relatedname_industry', blank=True)
    dindustry = models.ManyToManyField(Sectors, related_name='relatedname_dindustry', blank=True)

class Sectors(MPTTModel):
    sector = models.CharField(max_length=100)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

You need to verify that the signal handler is being triggered and to inspect the values of pk_set and action
Print here your output:

@receiver(m2m_changed, sender=Company.industry.through)
def video_category_changed(sender, instance, action, pk_set, **kwargs):
    print(f"Signal triggered with action: {action} and pk_set: {pk_set}")
    if action == "post_add":
        sectors = Sectors.objects.filter(id__in=pk_set)
        roots = set()
        for sector in sectors:
            root = sector.get_root()
            print(f"Processing sector: {sector}, root: {root}")
            if not instance.dindustry.filter(id=root.id).exists():
                instance.dindustry.add(root)
                print('data added to dindustry')