Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created March 2, 2021 09:53
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bmispelon/d7f4ecc710a3c2f5c6b07ba5453c4398 to your computer and use it in GitHub Desktop.
Save bmispelon/d7f4ecc710a3c2f5c6b07ba5453c4398 to your computer and use it in GitHub Desktop.
[Django ORM] Updating a JSONField based on the value of another field
"""
How to update JSONField based on the value of another field.
For example:
class MyModel(models.Model):
name = models.CharField(...)
data = models.JSONField()
How to update the MyModel table to store the `name` field inside the `data`
JSON object (under a key called `NAME`).
"""
from django.db.models import F, Func, JSONField, Value
class JSONBuildObject(Func):
"""
Build a new JSON object based on the given keys and values (alternating)
"""
output_field = JSONField()
function = 'jsonb_build_object'
class JSONConcat(Func):
"""
Merge all the given JSON objects together, returning a new one.
"""
output_field = JSONField()
arg_joiner = ' || '
template = '(%(expressions)s)'
MyModel.objects.update(data=JSONConcat(
F('data'),
JSONBuildObject(
Value('NAME'), # key
F('name'), # value
)
))
@sarajoha
Copy link

omg you saved my life, thanks, this is awesome! 🎉 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment