'Saving a JSON-Field with popped keys

I'm trying to delete all occurences of a certain key in a JSON-Field when a certain key is deleted.

What I've been trying is just popping all occurences of the given key in the json-field. However, saving a JSONField with a popped key doesn't seem to work - the data isn't changed on the Element-objects. Is there a way to do this?

class Element(models.Model):
  data = models.JSONField(default=dict, blank=True)

class Key(moedls.Model):
[...]
    def delete(self, *args, **kwargs):
        to_update = Element.objects.filter(data__has_key=self.slug)
        for element in to_update:
            element.data.pop(self.slug)
        GraphElement.objects.bulk_update(to_update, ["data"])
        super().delete(*args, **kwargs)

Edit: I just realized that this code actually seems to work - but just sometimes.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source