django m2m_changed无法正常工作

时间:2018-04-05 15:03:36

标签: python django signals models

我有简单的代码,bug无法正常工作! 将标记添加到未称为tag_update_count_use的内容后!

模型.py

class Tag(models.Model):
    count_use = models.PositiveIntegerField(_('count use'), default=0)

    def update_count_use(self, delta):
        self.count_use += delta
        self.save(update_fields=['count_use'])

class Content(models.Model):
    tags = models.ManyToManyField('Tag', blank=True, verbose_name=_('tags'))

signals.py

from django.db.models.signals import m2m_changed
from django.dispatch import receiver

@receiver(m2m_changed, sender=Content.tags)
def tag_update_count_use(sender, **kwargs):
    print(kwargs)
    return kwargs

__初始化__。PY

default_app_config = 'content.apps.ContentConfig'

apps.py

class ContentConfig(AppConfig):
    name = 'content'
    verbose_name = _('content')

    def ready(self):
        import content.signals

根据https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed我将代码更改为:

@receiver(m2m_changed, sender=Content.tags.though)

但是我收到了这个错误:

AttributeError: 'ManyToManyDescriptor' object has no attribute 'though'

1 个答案:

答案 0 :(得分:1)

您错过了r中的through。尝试:

@receiver(m2m_changed, sender=Content.tags.through)