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:
- Table was altered and dindustry was newly created.
- 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')