SqlAlchemy(Flask + Postgres):如何仅更新json字段的特定属性?

编程入门 行业动态 更新时间:2024-10-26 12:29:02
本文介绍了SqlAlchemy(Flask + Postgres):如何仅更新json字段的特定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个表,其中的一列声明为json,我需要通过将键值添加到json值来更新记录.

I have a table that has one column declared as a json and I need to update records by adding a key-value to the json value.

模型

class User(db.Model): __tablename__ = 'users' loginId = db.Column(db.String(128), nullable=False, primary_key=True) _password = db.Column(db.String(128), nullable=True) views = db.Column(JSON, nullable=True)

控制器

@mod_event.route('/view', methods=['POST']) def view(): try: params = request.json loginId = params['dream']['loginId'] users.update().\ where(users.c.loginId==loginId).\ values(views=<query>))

假定views中的当前值为{'1001':1} 如果必须将views更新为-

Assume current value in views is {'1001' : 1} What should be the query if views has to be updated to -

  • {'1001':2}
  • {'1001':1,'1002':1}

如果我不想先查询该值,请更改并更新回来.

if i don't want to query the value first, change and update back.

我很难确定如何在单个查询中执行此操作,请帮忙,谢谢!

I'm having a hard time figuring how to do this in a single query, please help, thanks!

推荐答案

如果使用的是JSONB,则可以使用jsonb_set函数

if you are using JSONB, you can use the jsonb_set function

(table .update() .values(views=func.jsonb_set(table.c.views, '{%s}' % '1002', 1)) .where(...))

如果您要从其他列插入

(table .update() .values(views=func.jsonb_set(table.c.views, '{%s}' % '1002', other_table.c.other_column.cast(String).cast(JSONB))) .where(...))

更多推荐

SqlAlchemy(Flask + Postgres):如何仅更新json字段的特定属性?

本文发布于:2023-10-26 22:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   属性   Flask   SqlAlchemy   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!