python - 我正在尝试使用 SQLAlchemy 作为 db.session 在烧瓶应用程序中表示 sql 连接
问题描述
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 ()
生成一个包含元组的列表?;[(< 0x101f039d0 处的主.LEASES 对象>,< 0x101f0e410 处的主.AP_INFO 对象>)]
试图确定如何修改 db.session 或从生成的内容中提取数据。
解决方案
看起来您可能想要使用.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
返回 a ResultProxy
,然后您可以使用它来调用ResultProxy.fetchone()
。
但是,您的第二个示例使用db.Session
uses Query.all()
,它始终返回包含在列表中的结果:
all() Return the results represented by this Query as a list.
如果您知道您只期待一个结果,请使用Query.one()
orQuery.one_or_none
代替。
或者,如果您的查询可能返回多个结果,但您只想要第一个,则Query.first()
推荐阅读
- android - 当任何其他应用程序在 Android 中使用麦克风时,如何检测音频/麦克风正在使用中?
- apache-spark - 给定一个类似 csv 的字符串,如何加载到 Spark 数据帧中?
- google-cloud-platform - GCP VPC 对等互连活动但 ping 失败
- javascript - 创建一个带有 2 个执行功能的按钮的模式,但我想将与返回 false 的函数绑定的按钮变灰
- c - 如何通过检查条件来打破循环
- python - RuntimeError(f"Directory '{directory}' 不存在") RuntimeError: Directory 'app/static' 不存在
- google-earth-engine - GEE - “NDVI”未在此范围内定义
- mongodb - MongoError:当被 lambda 调用时,池被破坏,但不是由来自同一服务器的代码
- javascript - 如何通过jquery中的json响应进行迭代
- reactjs - 在 Gatsby 中完成 prefetfcing 时,有什么方法可以触发函数?