Skip to content

Instantly share code, notes, and snippets.

@DmytroLitvinov
Forked from bmispelon/update.py
Last active March 28, 2021 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmytroLitvinov/82d26ed773de658299eeb1863b40caf2 to your computer and use it in GitHub Desktop.
Save DmytroLitvinov/82d26ed773de658299eeb1863b40caf2 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
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment