You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django新增M2M字段dindustry调用instance.add()不生效求助

Django多对多字段信号接收器异常排查

问题描述

将两段代码中的industry和dindustry字段互换后,Code 1运行正常且能正确更新数据库,但Code 2无法完成数据库更新操作,恳请协助排查原因。

注意事项

  • 已修改数据表,dindustry为新增字段
  • 无迁移问题,可通过Django Admin向industry和dindustry字段添加记录

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')

模型定义

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')

内容的提问来源于stack exchange,提问作者skb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:39:55