[Fixed]-Updating JSONField in django rest framework

16👍

thing = Thing.objects.get(name="...")
thing.properties['color'] = 'green'
thing.save()
👤serg

20👍

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",
    )
)

2👍

For your model:

class Thing(models.Model):
    name = models.CharField()
    properties = JSONField()

If you need to update bunch of entries, you can do the following:

Thing.objects.update(
    properties=RawSQL("jsonb_set(properties, '{color}', 'green', true)", [])
)

color: green will be inserted, if not exists.

Welcome to PostgreSQL docs for more information about jsonb_set.

0👍

The next syntax works for me,

  • Django==2.2.19
  • Postgres==12.0.6
from django.db.models.expressions import RawSQL
Thing.objects.update(properties=RawSQL("""jsonb_set(properties, \'{"name"}\',\'"name value"\', true)""", []))

-4👍

Leave a comment