m2m_changed不触发自定义“直通”模型

时间:2012-09-09 13:38:50

标签: django django-models django-signals

我在throughWishlist之间为ManyToManyField设置了自定义Product中介模型:

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信号将被触发。

1 个答案:

答案 0 :(得分:0)

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

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