SQLAlchemy使用json_set更新特定的JSON字段

时间:2019-05-20 10:44:50

标签: sql json sqlite sqlalchemy mysql-json

我打算使用func函数来更新Sqlalchemy中的特定JSON字段,但是我遇到了一些问题,这是我的代码来更新字段:

self.db.query(TestModel).filter(TestModel.test_id == self._test_id).update(
    {field_name: func.json_set(
        field_name,
        "$." + key,
        formatted_val)}
    , synchronize_session='fetch'
)
self.db.commit()

我运行了上面的代码并得到了错误:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) malformed JSON

所以,我去检查日志,发现Sqlalchemy形成了一个像这样的SQL子句:

UPDATE test_model SET field_name=json_set('field_name', '$.keyname', 'value') WHERE test_model.test_id = 1;

问题是Sqlalchemy不应使用'field_name'来指定字段,而应该使用field_name来指定字段,而我尝试在sql客户端中运行以下已更正的sql子句:

UPDATE test_model SET field_name=json_set(field_name, '$.keyname', 'value') WHERE test_model.test_id = 1;

可以找到

我只是想知道如何使Sqlalchemy从'field_name'field_name的正确字段?

请帮助 谢谢

1 个答案:

答案 0 :(得分:0)

您应该将第一个名为模型的参数传递给函数 private func fetchReplies(for comment: Comment, completionHandler: @escaping ([Comment?]) -> Void) { var replies = [Comment?](repeating: nil, count: comment.repliesIDs!.count) let group = DispatchGroup() // local var for (replyIndex, replyID) in comment.repliesIDs!.enumerated() { let replyURL = URL(string: "https://hacker-news.firebaseio.com/v0/item/\(replyID).json")! group.enter() URLSession.shared.dataTask(with: replyURL) { data, _, _ in guard let data = data else { group.leave() // leave on failure, too return } do { let reply = try self.jsonDecoder.decode(Comment.self, from: data) replies[replyIndex] = reply if reply.repliesIDs != nil { self.fetchReplies(for: reply) { replies in replies[replyIndex].replies = replies group.leave() // if reply.replieIDs was not nil, we must not `leave` until this is done } } else { group.leave() // leave if reply.repliesIDs was nil } } catch { group.leave() // leave on failure, too print(error) } }.resume() } dispatchGroup.notify(queue: .main) { // do this on main to avoid synchronization headaches completionHandler(replies) } }

func.json_set