I currently became familiar with using JSONField in django rest-framework, but I could not find any straight forward way to update a key in a stored json. There are many ways to filter JSONField depends on its internal keys, but it seems that there is no way to change, update or delete a key from already stored JSONField. But it seems that postgres can do some modifications on json keys as this answer explained.
Is there any function which is able to do modifications on JSONFields. If there is not any direct command to do this, what is the best way to implement modifications of a JSONField?
Edit:
As an example if I have a model like this:
class Thing(models.Model):
name = models.CharField()
properties = JSONField()
And in properties
I stored a json like this :
{
"color" : "red",
"size" : "large",
"cost" : 1234
}
Then I want to change the color to "green" by using django commands.
Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.
jsonfield is a reusable model field that allows you to store validated JSON, automatically handling serialization to and from the database. To use, add jsonfield. JSONField to one of your models. Note: django. contrib.
The JsonResponse transforms the data you pass to it to a JSON string and sets the content type HTTP header to application/json . To return JSON data from a Django view you swap out the HttpResponse for JsonResponse and pass it the data that needs to be transformed to JSON.
thing = Thing.objects.get(name="...")
thing.properties['color'] = 'green'
thing.save()
The approach with jsonb_set
from @tarasinf and @Vladius001 does also work with Django's Func expression.
from django.db.models import F, Func, Value, JSONField
Thing.objects.update(
properties=Func(
F("properties"),
Value(["color"]),
Value("green", JSONField()),
function="jsonb_set",
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With