使用 SQLAlchemy 在 MySQL 上的 JSON 列中查询数组

Querying an array in a JSON column on MySQL with SQLAlchemy

我有以下代码:

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'

匹配的项目的 属性

我假设您正在参考这一行,您不想在其中使用 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")