当前位置:Gxlcms > 数据库问题 > sqlalchemy--group_concat的使用

sqlalchemy--group_concat的使用

时间:2021-07-01 10:21:17 帮助过:1人阅读

select device_type, group_concat(id) from otherequipment group by device_type; +-------------+---------------------+ | device_type | group_concat(id) | +-------------+---------------------+ | 1 | 1,11,9,13,6,5,4,3,2 | | 2 | 10,12 | | 3 | 8,7 | +-------------+---------------------+ 3 rows in set (0.00 sec)

  按照类型划分设备,对比一下上面的数据,是不是一下子全出来了。

  但在sqlalchemy中如何使用呢?sqlalchemy有个func,里面包含各种sql函数。我们试用一下吧。

  sqlalchemy的model如下,

  

class OtherEquipment(Base):
    """
    其他公司普通设备
    """
    __tablename__ = otherequipment

    id = Column(id, Integer, primary_key=True)
    device_type = Column(device_type, SmallInteger, index=True, default=1)

    name = Column(name, String(40), index=True)
    position = Column(position, String(40), nullable=True)

  那获取这些设备的对象就很好写咯,

es = db_session.query(OtherEquipment.device_type, func.group_concat(OtherEquipment.id)).group_by(OtherEquipment.device_type).all()
all_equipments = []
for l in es:
    device_type, ids = l
    ids = ids.split(,)
    equipments = [OtherEquipment.query.get(e_id) for e_id in ids]
    all_equipments.append((device_type, equipments))
all_equipments就是其所有设备的结构图,打印一下,结果如下:
[(1, [外部设备1, 外部设备11, 外部设备9, 外部设备13, 外部设备6, 外部设备5, 外部设备4, 外部设备3, 外部设备2]), (2, [外部设备10, 外部设备12]), (3, [外部设备8, 外部设备7])]

  这样,客户端直接拿到接口的数据,就可以直接展示,不需要自己轮询,再去分析了。

 

 

sqlalchemy--group_concat的使用

标签:

人气教程排行