How can I replace a substring with a string in django nested in a JSONField?
If I have a model:
class MyModel(Model):
properties = JSONField()
And I have instances where the properties
look like this:
{"a": {"b": ["some text A"]}}
{"a": {"b": ["some other text A"]}}
{"a": {"b": ["some text A"]}}
How do I bulk-update these model instances, replacing the string "A" with "B"? I would assume it would be something like this:
MyModel.objects.update(
properties=Func(
F("properties"),
Value("{a,b,0}"),
Cast(
Replace(Cast(F("a__b__0"), CharField()), Value("A"), Value("B")),
JSONField(),
),
function="jsonb_set",
)
)
It doesn't quite work though. I think I'm just missing a proper reference to the field (F("a__b__0")
is invalid).