I have a Django JSONField on PostgreSQL which contains a dictionary, and I would like to use the queryset.update() to bulk update several keys with values. I know how to do it for one value in a JSONField (and for multiple fields in general):
from django.db.models import Func, Value, CharField, FloatField, F, IntegerField
class JSONBSet(Func):
"""
Update the value of a JSONField for a specific key.
"""
function = 'JSONB_SET'
arity = 4
output_field = CharField()
def __init__(self, field, path, value, create: bool = True):
path = Value('{{{0}}}'.format(','.join(path)))
create = Value(create)
super().__init__(field, path, value, create)
This seems to work - with some gaps as per my other question - like this:
# This example sets the 'nestedkey' to numeric 199.
queryset.update(inputs=JSONBSet('inputs', ['nestedkey_1'], Value("199"), False))
But if I now wanted to update a second nestedkey_2
inside the same inputs
, I obviously cannot use the inputs
argument twice like this:
queryset.update(inputs=JSONBSet(...'nestedkey_1'...), inputs=JSONBSet(...'nestedkey_2'...)
Is there a way to do this?