假设我有一个如此定义的模型:
class DstEntry(Base):
__tablename__ = 'dst_entry'
id = Column('id', DBKeyType, primary_key=True)
name = Column(String(64))
ip_addr = Column(IPAddress)
logical_device_ip = Column(String(64))
我有这样的数据:
id name ip_addr logical_device_ip
--------------------------------------------------
1 l3dst 3.3.3.3/32 192.168.99.151
2 httpdst 1.1.1.1/32 192.168.99.152 <===
3 httpdst2 2.2.2.0/24 192.168.99.151
4 dddd 1.1.1.1/32 192.168.99.153 <===
5 httpdst 1.1.1.1/32 192.168.99.151 <===
6 aadst 4.4.4.4/32 192.168.99.153
我希望能够执行查询以最终获得告诉我的信息:
ip_addr logical_device_ip
--------------------------------------------------
1.1.1.1/32 192.168.99.151, 192.168.99.152, 192.168.99.153
3.3.3.3/32 192.168.99.151
2.2.2.0/24 192.168.99.151
4.4.4.4/32 192.168.99.153
如何使用sqlalchemy执行此操作?
答案 0 :(得分:0)
试试这个:
res = session.query(
DstEntry.ip_addr,
func.group_concat(DstEntry.logical_device_ip)
).group_by(DstEntry.ip_addr)
for r in res:
print r
注意:强>
logical_device_ip
与,
连接为分隔符。如果要在分隔符中添加空格字符,请执行此操作
res = session.query(
DstEntry.ip_addr,
func.group_concat(DstEntry.logical_device_ip.op('SEPARATOR')(', '))
).group_by(DstEntry.ip_addr)
MySQL的原始SQL查询是:
SELECT ip_addr,
GROUP_CONCAT(logical_device_ip) AS logical_device_ip
FROM dst_entry
GROUP BY ip_addr;