版本:Django 1.10和Postgres 9.6
我试图修改嵌套的JSONField键,而不需要往返Python。原因是避免竞争条件和多个查询用不同的更新覆盖相同的字段。
我试图链接这些方法,希望Django可以进行单个查询但是它被记录为两个:
原始字段值(仅限演示,实际数据更复杂):
from exampleapp.models import AdhocTask
record = AdhocTask.objects.get(id=1)
print(record.log)
> {'demo_key': 'original'}
查询:
from django.db.models import F
from django.db.models.expressions import RawSQL
(AdhocTask.objects.filter(id=25)
.annotate(temp=RawSQL(
# `jsonb_set` gets current json value of `log` field,
# take a the nominated key ("demo key" in this example)
# and replaces the value with the json provided ("new value")
# Raw sql is wrapped in triple quotes to avoid escaping each quote
"""jsonb_set(log, '{"demo_key"}','"new value"', false)""",[]))
# Finally, get the temp field and overwrite the original JSONField
.update(log=F('temp’))
)
查询记录(将其显示为两个单独的查询):
from django.db import connection
print(connection.queries)
> {'sql': 'SELECT "exampleapp_adhoctask"."id", "exampleapp_adhoctask"."description", "exampleapp_adhoctask"."log" FROM "exampleapp_adhoctask" WHERE "exampleapp_adhoctask"."id" = 1', 'time': '0.001'},
> {'sql': 'UPDATE "exampleapp_adhoctask" SET "log" = (jsonb_set(log, \'{"demo_key"}\',\'"new value"\', false)) WHERE "exampleapp_adhoctask"."id" = 1', 'time': '0.001'}]
答案 0 :(得分:5)
没有RawSQL
会更好。
以下是如何操作:
from django.db.models.expressions import Func
class ReplaceValue(Func):
function = 'jsonb_set'
template = "%(function)s(%(expressions)s, '{\"%(keyname)s\"}','\"%(new_value)s\"', %(create_missing)s)"
arity = 1
def __init__(
self, expression: str, keyname: str, new_value: str,
create_missing: bool=False, **extra,
):
super().__init__(
expression,
keyname=keyname,
new_value=new_value,
create_missing='true' if create_missing else 'false',
**extra,
)
AdhocTask.objects.filter(id=25) \
.update(log=ReplaceValue(
'log',
keyname='demo_key',
new_value='another value',
create_missing=False,
)
ReplaceValue.template
与原始SQL语句相同,只是参数化。
(jsonb_set(log, \'{"demo_key"}\',\'"another value"\', false))
现在为jsonb_set("exampleapp.adhoctask"."log", \'{"demo_key"}\',\'"another value"\', false)
。括号已经消失(您可以通过将其添加到模板中来取回它们)并以不同的方式引用log
。
任何对jsonb_set
更多详情感兴趣的人都应该查看postgres文档中的表9-45:https://www.postgresql.org/docs/9.6/static/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE
答案 1 :(得分:2)
橡皮鸭调试处于最佳状态 - 在写这个问题时,我已经意识到了解决方案。留下答案,希望将来帮助某人:
查看查询,我意识到RawSQL实际上被推迟到第二个查询,所以我所做的只是将RawSQL
存储为子查询以供以后执行。
<强>解决方案强>:
完全跳过annotate
步骤,并将RawSQL
表达式直接用于.update()
调用。允许您动态更新数据库服务器上的PostgresQL jsonb子键,而不会覆盖整个字段:
(AdhocTask.objects.filter(id=25)
.update(log=RawSQL(
"""jsonb_set(log, '{"demo_key"}','"another value"', false)""",[])
)
)
> 1 # Success
print(connection.queries)
> {'sql': 'UPDATE "exampleapp_adhoctask" SET "log" = (jsonb_set(log, \'{"demo_key"}\',\'"another value"\', false)) WHERE "exampleapp_adhoctask"."id" = 1', 'time': '0.001'}]
print(AdhocTask.objects.get(id=1).log)
> {'demo_key': 'another value'}