[SQLAlchemy求助] 'RowProxy' object does not support item assignment

2013-07-14 22:16:27 +08:00
 hustlzp
在一个比较小的Flask项目中使用SQLAlchemy,没有用ORM,只用了SQL Expression Language。

业务逻辑中有mtype(主类别)和stype(子类别)之分,一个mtype包括多个stype。

现在需要查询所有的mtype,并显示每个mtype的所有stype,代码如下:

mtypes = Type.get_mtypes()
for m in mtypes:
m['stypes'] = Type.get_stypes(m['MainTypeID'])

其中get_mtypes和get_stypes的定义如下:

class Type:
@staticmethod
def get_mtypes():
return g.conn.execute(
select([mtype])
.order_by(mtype.c.ShowOrder.asc())).fetchall()

@staticmethod
def get_mtype_by_id(mtype_id):
return g.conn.execute(
select([mtype])
.where(mtype.c.MainTypeID == mtype_id)).fetchone()

报错:'RowProxy' object does not support item assignment

文档对RowProxy的描述如下:

Proxy values from a single cursor row.

Mostly follows “ordered dictionary” behavior, mapping result values to the string-based column name, the
integer position of the result in the row, as well as Column instances which can be mapped to the original
Columns that produced this result set (for results that correspond to constructed SQL expressions).

好像这个ordered dictionary是无法赋予其新的key:value。目前的解决方法是,在赋值前手动将所有的RowProxy转换为dict类型:

mtypes = [dict[m] for m in Type.get_mtypes()]
for m in mtypes:
m['stypes'] = Type.get_stypes(m['MainTypeID'])

这样就不会报错了,不过每次都要额外加一个转换,感觉很蛋疼。

目前想到的简化方法是,在获取get_stypes这个函数里面就把所有的stypes通过子查询找到,而不是在获取了RowProxy后再去给它赋值。

大家还有什么好的建议没?
7044 次点击
所在节点    Python
3 条回复
keakon
2013-07-15 01:35:06 +08:00
这表你反正都得全读出来,为什么不直接一次读出来,再在应用里处理?循环查询数据库会被骂死的…
hustlzp
2013-07-15 07:48:19 +08:00
@keakon 懂了...一次在数据层读出来给业务层就好...
Linxing
2018-03-11 17:05:27 +08:00
老铁 我想问下 RowProxy 如何去做分页 只能自己写?想跟 datatable 结合下

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/75760

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX