Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating JSONField in django rest framework

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.

like image 840
motam Avatar asked Apr 17 '16 18:04

motam


People also ask

How do I update user details in Django REST framework?

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.

What is a JSONField?

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.

How do I return a JSON response in Django?

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.


2 Answers

thing = Thing.objects.get(name="...")
thing.properties['color'] = 'green'
thing.save()
like image 80
serg Avatar answered Sep 18 '22 17:09

serg


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",
    )
)
like image 39
foonicorn Avatar answered Sep 21 '22 17:09

foonicorn