首页 > 解决方案 > 我正在尝试使用 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 或从生成的内容中提取数据。

标签: pythonflask-sqlalchemy

解决方案


看起来您可能想要使用.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.Sessionuses Query.all(),它始终返回包含在列表中的结果:

all()

    Return the results represented by this Query as a list.

如果您知道您只期待一个结果,请使用Query.one()orQuery.one_or_none代替。

或者,如果您的查询可能返回多个结果,但您只想要第一个,则Query.first()


推荐阅读