Write Django QuerySet that remove all whitespace from specific Keys within a JSONFIELD

I would like to write a Django QuerySet that removes whitespaces from Specific Keys within a JsonField.

I have a django model with a JsonField type.

MyModel(Model):
     a: str,
     properties: JSONField

this is an example of database lines :

a, properties

“first”, {“key_1”: “  key1value”, “key_2”:”key2value”, “key_3”: “  key_3”}
“second”, {“key_2”: “    key2   “}

and my queryset should update my data removing whitespace of specific key. So for Key_1 and Key_2 it will give me:

“first”, {“key_1”: “key1value”, “key_2”:”key2value”, “key_3”: “  key_3”}
    “second”, {“key_2”: “key2“}

I tried using

MyModel.objects.update(properties_key_1=F("propertieskey_1”).strip().lower(), propertieskey_2=F("properties_key_2”).strip().lower())

but I get an error:

==> result 
AttributeError: 'F' object has no attribute 'strip

I tried:

MyModel.objects.update(properties__key_1=RawSQL("properties->key_1->value", []).strip())
==> result 'RawSQL' object has no attribute 'strip'

I tried:

MyModel.objects.update(properties__key_1=RawSQL("TRIM(properties->asset_class->value)”)
==> 
    SyntaxError: positional argument follows keyword argument

Any idea please ? thx you

Back to Top