【问题标题】:Querying an array in a JSON column on MySQL with SQLAlchemy [closed]使用 SQLAlchemy 在 MySQL 上查询 JSON 列中的数组 [关闭]
【发布时间】:2021-07-24 23:58:13
【问题描述】:

我有以下代码:

class CabinetList(Resource):
def get(self):
    devices = Device.query.filter(Device.type == 'CABINET').all()
    return {'cabinets':list(x.json() for x in devices)}   

生成这个存储在 JSON MySql 列中的 JSON:

 {
   "cabinets":[
      {
         "id":4,
         "name":"Armario 1",
         "online":true,
         "setup":0.0,
         "type":"CABINET",
         "data":{
            "lockers":[
               {
                  "id":1,
                  "content":"Pala",
                  "enabled":true,
                  "busy":false
               },
               {
                  "id":2,
                  "content":"Azada",
                  "enabled":true,
                  "busy":false
               }
            ]
         }
      }
   ]
}

使用此代码,我可以更改所选索引的“忙碌”属性

def get(self, device_id, locker_id):

    if not 1 <= locker_id <= 32:
        return {'error': 'device not found'}, 404

    device = Device.query.filter(and_(Device.id == device_id, Device.type == 'CABINET')).first()
    if not device:
        return {'error': 'device not found'}, 404

    # Update the current status for the locker
    device.data['lockers'][0]['busy'] = True
    
    return {'cabinet': device.json()}

它有效,但我不想通过索引来引用该项目我想更改匹配其“id”的项目的属性

【问题讨论】:

    标签: python mysql json sqlalchemy flask-sqlalchemy


    【解决方案1】:

    我假设您正在参考这一行,您不想使用 0 作为索引来访问正确的储物柜:

    device.data['lockers'][0]['busy'] = True
    

    我认为最简单的解决方案是通过提供的locker_id 过滤储物柜:

    for locker in device.data['lockers']:
        if locker['id'] == locker_id:
            locker['busy'] = True
            break
    else:
        raise Exception("Locker not found")
    

    【讨论】:

    • 完美运行,解决方案非常简单,以至于我有点尴尬我自己没有找到它。第一个 python 项目。
    猜你喜欢
    • 2016-12-12
    • 2012-12-31
    • 2015-02-11
    • 2021-12-19
    • 2019-02-07
    • 1970-01-01
    • 2020-03-10
    • 2016-12-22
    • 2021-01-04
    相关资源
    最近更新 更多