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",
)
)
- Django OneToOneField default value
- Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking i
- Django models = business logic + data access? Or data access layer should be separated out from django model?
- How to construct django Q object matching none
- Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'
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)""", []))
- Django-admin: How to redirect to another URL after Object save?
- Multi-Tenant Django Application
- How can I set a minimum password length when using the built-in Django auth module?
- Reversing Django URLs With Extra Options
- Is there a way to combine behavior of SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE
-4👍
You can find better solution here
https://django-postgres-extensions.readthedocs.io/en/latest/json.html
- Django: Using Annotate, Count and Distinct on a Queryset
- Django – (OperationalError) FATAL: Ident authentication failed for user "username"
Source:stackexchange.com