【问题标题】:m2m_changed not trigger for custom "through" modelm2m_changed 不会触发自定义“通过”模型
【发布时间】:2012-09-02 14:28:18
【问题描述】:

我在 WishlistProduct 之间为 ManyToManyField 定制了一个 through 中间模型:

class Product(models.Model):
    name = models.CharField(max_length=255)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created', )

    def __unicode__(self):
        return self.name


class Wishlist(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=255)
    created = models.DateTimeField(auto_now_add=True)
    products = models.ManyToManyField(Product, through='WishlistProduct', null=True, blank=True)

    class Meta:
        ordering = ('-created', )

    def __unicode__(self):
        return self.name


class WishlistProduct(models.Model):
    wishlist = models.ForeignKey(Wishlist)
    product = models.ForeignKey(Product)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created', )

    def __unicode__(self):
        return u'%s in %s' % (self.product.name, self.wishlist.name)

还有一个m2m_changed 信号:

@receiver(m2m_changed, sender=Wishlist.products.through, dispatch_uid='m2m_changed_wishlist_products')
def m2m_changed_wishlist_products(sender, instance, action, *args, **kwargs):
    print(sender)
    print(action)

m2m_changed 信号不起作用,为什么?

但 WishlistProduct 的post_save 信号将被触发。

【问题讨论】:

    标签: django django-models django-signals


    【解决方案1】:

    您的信号可能正在被垃圾收集。将 weak=False 传递给 connect 方法。

    https://docs.djangoproject.com/en/dev/topics/signals/#listening-to-signals

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      相关资源
      最近更新 更多