Update: Thanks for the comment below, I'm updating the question.
I'm using a JSONField to store a list of elements in this format:
[{"name": "field1", "value": "100", type:"number"}, {"name": "field2", "value": "500", "type":"number"}]
I can have more keys, like "required","type", etc. The name it's unique.
This is my model:
from django.contrib.postgres.fields import JSONField
class MyModel(models.Model):
json_data = JSONField(default=list, null=True) # Create an empty list always
I have a form to update the values stored in json_data, I update the data like this:
obj = MyModel.objects.get(pk=1)
json = obj.json_data # [{"name": "field1", "value": "100", , type:"number"}, {"name": "field2", "value": "500", type:"number"}]
new_data = {"name": "field2", "value": "99", type:"number"} # data to update that comes from form
fields_not_updated = [field for field in json
if new_data['name'] != field['name']] # Create a list of elements that are not updated
fields_not_updated.append(new_data) # Add the new data, output: [{"name": "field1", "value": "100", type:"number"}, {"name": "field2", "value": "99", type:"number"}]
obj.json_data = fields_not_updated # set new json
obj.save() # save object
I was wondering if there is an easier or more efficient method to update the elements inside the list and save them in the JSONField using django functions or methods or directly using python.