apInfo = db.engine.execute(
"select L.circuit_id, L.remote_id, AP_I.vlan, AP_I.color
from leases as L, ap_info as AP_I
where L.circuit_id = AP_I.mac_address and
L.remote_id = '%s'; " % sm_mac_.remote_id[:17]).fetchone()
这将正确生成:(u'0a:00:3e:bb:76:54',u'0a:00:3e:bb:c1:f7',12,77(
我尝试代表为:
apInfo = db.session.query(LEASES, AP_INFO)
.filter(LEASES.circuit_id == AP_INFO.mac_address)
.filter(LEASES.remote_id == sm_mac_.remote_id[:17])
.all ()
生成一个包含元组的列表?;[(<main.LEASES对象位于0x101f039d0>,<main[/strong>.AP_INFO对象位于0x101 f0e410>(]
试图确定如何修改db.session或从生成的内容中提取数据。
这是有效的,但还没有完成!
ret = db.session.query(LEASES, AP_INFO)
.filter(LEASES.circuit_id == AP_INFO.mac_address)
.filter(LEASES.remote_id == sm_mac_.remote_id[:17])
.all ()
apInfo = (ret[0].LEASES.circuit_id,
ret[0].LEASES.remote_id,
ret[0].AP_INFO.vlan,
ret[0].AP_INFO.color)
我想找到一种直接返回查询值的方法;以改进查询。
看起来您可能想要使用.one()
而不是.all()
:
apInfo = db.session.query(LEASES, AP_INFO)
.filter(LEASES.circuit_id == AP_INFO.mac_address)
.filter(LEASES.remote_id == sm_mac_.remote_id[:17])
.one()
使用Engine
的第一个示例返回一个ResultProxy
,然后用它来调用ResultProxy.fetchone()
。
但是,使用db.Session
的第二个示例使用Query.all()
,总是返回封装在列表中的结果:
all() Return the results represented by this Query as a list.
如果您知道您只期望一个结果,请使用Query.one()
或Query.one_or_none
。
或者,如果您的查询可能返回多个结果,但您只想要第一个,则有Query.first()