Created
March 2, 2021 09:53
-
-
Save bmispelon/d7f4ecc710a3c2f5c6b07ba5453c4398 to your computer and use it in GitHub Desktop.
[Django ORM] Updating a JSONField based on the value of another field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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
omg you saved my life, thanks, this is awesome! 🎉 😊