防止m2m_changed更新父类的修改日期

时间:2018-09-02 14:32:16

标签: django django-models

我有一个名为Outfit的类,并且在该类中,有一个称为产品的多对多关系:

class Outfit(models.Model):
   products = models.ManyToManyField(Product,
                                  related_name='outfits',
                                  blank=True)
   created = models.DateTimeField(editable=False)
   modified = models.DateTimeField()

   class Meta:
   def save(self, *args, **kwargs):
    ''' On save, update timestamps '''
    if not self.id:
        self.created = timezone.now()
    self.modified = timezone.now()
    return super(Outfit, self).save(*args, **kwargs)

在产品模型中,我有一个名为product_outfit_count的变量,该变量基本上跟踪使用特定产品的服装数量。保存服装后,此信号称为:

m2m_changed.connect(update_product_outfit_count,
                sender=Outfit.products.through)

问题在于,当更新商品的着装数量时,衣服的修改日期也会改变。我该如何预防?

编辑: update_product_count方法:

def update_product_outfit_count_task(product_ids):
Product = apps.get_model('products.Product')
with transaction.atomic():
    for product in Product.objects.filter(pk__in=product_ids):
        product.outfit_count = product.outfits.count()
        product.save()

0 个答案:

没有答案