0

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.

Kevin Ramirez Zavalza
  • 1,629
  • 1
  • 22
  • 34
  • I assume that a field can only appear once, why not save it as a dictionary instead of a list of dictionaries? `{'field1': '100', 'field2': '500'}`, that would change your updating from `O(n)` to `O(1)`. – BoobyTrap May 20 '21 at 23:14
  • That is a good solution but I forgot to mention that I'm planning to add more keys to each element. – Kevin Ramirez Zavalza May 21 '21 at 00:10
  • Then you can add a list or dictionary for each field key. – BoobyTrap May 22 '21 at 14:10

0 Answers0