首页 > 解决方案 > TypeError:“类”对象不可迭代-flask/sqlalchemy/jinja

问题描述

我正在从数据库中检索数据,并且想将其放入表中。我正在使用 SQLAlchemy 和 SQLite 数据库。

这是我在 routes.py 中的代码:

headings = ('Name', 'Code')
classes = tuple(list(ClassName.query.filter_by(id=current_user.id).all()))
print(classes)
return render_template("view.html", headings=headings, classes=classes)

这是 view.html 中的代码:

      <div class="view-table">
        <table>
          <tr>
            {% for header in headings %}
            <th>{{ header }}</th>
            {% endfor %}
          </tr>
          {% for row in classes %}
          <tr>
              {% for cell in row %}
                <td>{{ cell }}</td>
              {% endfor %}
          </tr>
          {% endfor %}
        </table>
      </div>

每当我运行它时,我都会收到此错误:

TypeError: 'Class' object is not iterable

我正在关注本教程,这就是我将列表更改为元组的原因:https ://youtu.be/mCy52I4exTU

标签: pythonhtmlsqlitejinja2flask-sqlalchemy

解决方案


我找到了答案。

在我的routes.py中,我这样做了:

classes = Classes.query.filter_by(classAdminID=current_user.id).all()

在我的view.html中,我这样做了:

      <div class="view-table">
        <table>
          <tr>
            {% for header in headings %}
            <th>{{ header }}</th>
            {% endfor %}
          </tr>
          {% for row in classes %}
          <tr>
                <td>{{ row.Name }}</td>
                <td>{{ row.Code }}</td>
          </tr>
          {% endfor %}
        </table>
      </div>

我在此视频中找到了解决方案:https ://youtu.be/hbDRTZarMUw


推荐阅读