V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
hustlzp
V2EX  ›  Python

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

  •  
  •   hustlzp ·
    hustlzp · 2013-07-14 22:16:27 +08:00 · 7031 次点击
    这是一个创建于 3910 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在一个比较小的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后再去给它赋值。

    大家还有什么好的建议没?
    3 条回复    2018-03-11 17:05:27 +08:00
    keakon
        1
    keakon  
       2013-07-15 01:35:06 +08:00   ❤️ 1
    这表你反正都得全读出来,为什么不直接一次读出来,再在应用里处理?循环查询数据库会被骂死的…
    hustlzp
        2
    hustlzp  
    OP
       2013-07-15 07:48:19 +08:00
    @keakon 懂了...一次在数据层读出来给业务层就好...
    Linxing
        3
    Linxing  
       2018-03-11 17:05:27 +08:00
    老铁 我想问下 RowProxy 如何去做分页 只能自己写?想跟 datatable 结合下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5412 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:59 · PVG 16:59 · LAX 01:59 · JFK 04:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.