【问题标题】:sqlalchemy class object not iterablesqlalchemy 类对象不可迭代
【发布时间】:2016-05-30 03:42:07
【问题描述】:

我正在尝试从我的问题表中检索问题,但我收到问题类对象不可迭代的错误。给出此错误的代码示例是

def get(self):
    for quser in session.query(questions).all():

        return jsonify(quser)

我需要在这里做什么。我对此进行了很多搜索,但无法解决。请帮忙。

【问题讨论】:

  • session 指的是什么?
  • Questions 类对象不可迭代..这是错误

标签: python sqlalchemy flask-restful


【解决方案1】:

如果我正确理解你想要什么...

你可以为你的类实现这个方法:

def to_dict(self):
    if getattr(self, '_sa_free', None):
        return {k: v for k, v in self.__dict__.iteritems()}
    attr_names = getattr(self.__class__, '__attr_names', None)
    if not attr_names:
        attr_names = [prop.key for prop in
                      class_mapper(self.__class__).iterate_properties if
                      isinstance(prop, ColumnProperty) and not prop.key.startswith('_')]
        for attr in dir(self.__class__):
            if isinstance(getattr(self.__class__, attr), (InstrumentedAttribute, property)) \
                    and not attr.startswith('_'):
                attr_names.append(attr)
        setattr(self.__class__, '__attr_names', list(set(attr_names)))

    return {attr: getattr(self, attr) for attr in attr_names}

然后:

return jsonify(**quser.to_dict())

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2021-08-23
    • 2021-08-20
    • 1970-01-01
    • 2015-02-06
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多