Updating M2M Model after save

Viewed 54

I have two models

class Item(models.Model):
    name = models.CharField(max_length=50)
    sku = models.CharField(max_length=50)
    description = models.TextField(max_length=100, blank=True)
    status = models.IntegerField(choices=TRUE_FALSE_CHOICES, default='1')

    def __str__(self):
        return self.name

class Location(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField(max_length=100)
    items = models.ManyToManyField(Item, blank=True)

    def __str__(self):
        return self.name

so what im trying to achieve is when you save a location all items assigned to that location should change status to 0. Any ideas on how can I do that ?

EDIT: I have used a signal to change the value when it's added

@receiver(models.signals.m2m_changed, sender=Location.items.through)
def items_changed(sender, instance, action, **kwargs):
    if action == 'post_add':
        instance.items.all().update(status='0')

but now how can I revert the status if the item is removed ?

1 Answers

You can try this.

location_obj.items.all().update(status='0')
Related