Skip to content

Instantly share code, notes, and snippets.

@marcgibbons
Last active September 12, 2023 19:05
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcgibbons/22bf6a67a93908ef93bb27d18b229611 to your computer and use it in GitHub Desktop.
Save marcgibbons/22bf6a67a93908ef93bb27d18b229611 to your computer and use it in GitHub Desktop.
Expression to concatenate Django Postgres JSONField
from django.db.models.expressions import CombinedExpression, F, Value
from django.contrib.postgres.fields import JSONField
expression = CombinedExpression(
F('my_json_field'),
'||',
Value({'fizz': 'buzz'}, JSONField())
)
@nilox94
Copy link

nilox94 commented Apr 21, 2021

nice!
I wanted to extend the JSON field looking up another field, so I used it with JSONObject like this

from django.db.models.functions import JSONObject
from django.db.models.expressions import CombinedExpression, F

# {
#   "my_json_field": { "foo": "bar" },
#   "non_json_field": "buzz"
# }

expression =  CombinedExpression(
    F('my_json_field'), 
    '||', 
    JSONObject(fizz=F('non_json_field'))
)

# {
#   "foo": "bar",
#   "fizz": "buzz"
# }

@viraj071
Copy link

Does this overwrite keys that already exist in the JSON field?

@nilox94
Copy link

nilox94 commented Mar 25, 2023

yes, it's just the Postgres jsonb concatenation operator (||).

Concatenating two objects generates an object containing the union of their keys, taking the second object's value when there are duplicate keys.

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