Django(2.0.6):更新信号中的m2m相关对象

时间:2018-06-03 18:25:55

标签: python django

我试图从m2m字段中获取更新的相关对象列表

E.g。我有以下模型

class Product(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(blank=True, unique=True)
    description = models.TextField(default='N/A')
    price = models.DecimalField(decimal_places=2, max_digits=20, default=10.00)
    image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
    featured = models.BooleanField(default=False)
    active = models.BooleanField(default=True)
    category = models.CharField(blank=True, max_length=20, choices=CATEGORIES)
    size = models.CharField(max_length=100, choices=AVAILABLE_SIZE, blank=True)
    choice = models.CharField(max_length=100, choices=AVAILABLE_CHOICE, blank=True)

    objects = ProductManager()

    def get_absolute_url(self):
        return "/products/{slug}/".format(slug=self.slug)

    def __str__(self):
        return self.title

class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=True)
    products = models.ManyToManyField(Product, blank=True)
    total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
    subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    objects = CartManager()

    def __str__(self):
        return str(self.id)

现在我更新我的"产品"通过django管理员只需删除和添加项目。

所以我希望下面的信号会打印更新的产品(我刚添加/删除了)。但是,我仍然可以获得所有产品(产品型号的所有产品)

def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs):
    if action == 'post_add' or action == 'post_remove' or action == 'post_clear':
        print(action)
        products = instance.products.all()
        print(products)
        total = 0
        for x in products:
            total += x.price
        if instance.subtotal != total:
            instance.subtotal = total
            instance.save()


m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through)

我是django的新手,任何人都可以获得一些帮助。

1 个答案:

答案 0 :(得分:0)

您需要使用pk_set

尝试:

pk_set = kwargs.pop('pk_set', None)

对于pre_add,post_add,pre_remove和post_remove操作,这是一组已添加到关系中或从关系中删除的主键值。

对于pre_clear和post_clear操作,这是None。

docs