How to append a list inside of a dict from a JSONFeild in django

I want to use get_or_create() to search for an object. If it doesn't exist, it gets created. If it does exist, I want to update its metadata which is stored as a JSONFeild.

Lets say we have this class and object:

Class Customer(models.Model):
    first_name = models.CharField(max_length=32, blank=True, db_index=True)
    last_name = models.CharField(max_length=32, blank=True, db_index=True)
    metadata = models.JSONField(default=dict, blank=True)

Customer.objects.create(
    first_name="John", 
    last_name="Doe",
    metadata ={
        "customer_created":"2022_08_06",
        "address_list":["123 Street"],
    },
)

Now we want to add another customer, but if it already exists, we just want to append the list in metadata["address_list"]

obj, created = Customer.objects.get_or_create(
    first_name="John",
    last_name="Doe",
    defaults={
        'metadata':{
            "customer_created": "2022_09_26",
            "adress_list": ["321 Avenue"],
    }
)

Would obj.medata["address_list"].append(["321 Avenue"]) work or do I need to copy the list, append it, then update metadata? Which is correct?

if not created:
    obj.metadata["address_list"].append(["321 Avenue"])

or

if not created:
    addresses = obj.medata["address_list"]
    addresses.append(["321 Avenue"])
    obj.metadata["address_list"] = addresses
    

I'm new to django; is there a better way to do this? I am not allowed to change the Customer class but I can change how I structure the metadata dict

Back to Top