我有一个postgresql(v.9.5)表,称为使用sqlalchemy core定义的产品:
products = Table("products", metadata,
Column("id", Integer, primary_key=True),
Column("name", String, nullable=False, unique=True),
Column("description", String),
Column("list_price", Float),
Column("xdata", JSON))
假设表中的日期添加如下:
id | name | description | list_price | xdata
----+------------+---------------------------+------------+--------------------------------
24 | Product323 | description of product332 | 6000 | [{"category": 1, "uom": "kg"}]
使用API编辑代码如下:
def edit_product(product_id):
if 'id' in session:
exist_data = {}
mkeys = []
s = select([products]).where(products.c.id == product_id)
rs = g.conn.execute(s)
if rs.rowcount == 1:
data = request.get_json(force=True)
for r in rs:
exist_data = dict(r)
try:
print exist_data, 'exist_data'
stmt = products.update().values(data).\
where(products.c.id == product_id)
rs1 = g.conn.execute(stmt)
return jsonify({'id': "Product details modified"}), 204
except Exception, e:
print e
return jsonify(
{'message': "Couldn't modify details / Duplicate"}), 400
return jsonify({'message': "UNAUTHORIZED"}), 401
假设我只想修改"类别"表格的xdata列中的值,不会打扰" uom"属性及其价值,这是实现它的最佳方式吗?我已经尝试了'for循环'要获取现有值的属性,请使用传递的属性值进行检查更改以进行更新。我相信有比这更好的方法。请恢复为简化此
所需的更改答案 0 :(得分:1)
Postgresql提供了jsonb_set()
函数,用于用新值替换jsonb
的一部分。您的专栏使用的是json
类型,但只需使用简单的转换即可。
from sqlalchemy.dialects.postgresql import JSON, JSONB, array
import json
def edit_product(product_id):
...
# If xdata is present, replace with a jsonb_set() function expression
if 'xdata' in data:
# Hard coded path that expects a certain structure
data['xdata'] = func.jsonb_set(
products.c.xdata.cast(JSONB),
array(['0', 'category']),
# A bit ugly, yes, but the 3rd argument to jsonb_set() has type
# jsonb, and so the passed literal must be convertible to that
json.dumps(data['xdata'][0]['category'])).cast(JSON)
在给定一些结构的情况下,您还可以设置一个通用助手来创建对jsonb_set()
的嵌套调用:
import json
from sqlalchemy.dialects.postgresql import array
def to_jsonb_set(target, value, create_missing=True, path=()):
expr = target
if isinstance(value, dict):
for k, v in value.items():
expr = to_jsonb_set(expr, v, create_missing, (*path, k))
elif isinstance(value, list):
for i, v in enumerate(value):
expr = to_jsonb_set(expr, v, create_missing, (*path, i))
else:
expr = func.jsonb_set(
expr,
array([str(p) for p in path]),
json.dumps(value),
create_missing)
return expr
但可能过度了。