Search code examples
pythondjangopython-3.xdjango-views

Is it possible to increment a value with F in a json field in django?


Is it possible to increment a value with F in a json field in django?

I have an object that contains a json field and I have some keys in it.

Is it possible to increment the key value inside a json used F?

Thank you for all.

credits = Company.objects.filter().first()
credits.meta_data = F('meta_data')['credits'] + 1
credits.save()

Solution

  • Not sure what F is, but given you meta_data is a valid JSON object, you can manipulate it with json library, for instance:

    a = json.loads("{\"a\":1}")
    #or a = json.loads(credits.meta_data)
    print(a)
    a["a"] = a["a"]+1
    print(a)
    
    {'a': 1}
    {'a': 2}
    

    You want to be careful (handle exceptions and ensure you save valid json content into this field), because even when you are using postgresql-specific json field, it does not guarantee that you are getting a properly formatted json objects from it.