无法在视图中使用SQLAlchemy模型对象

时间:2017-03-05 21:59:12

标签: python flask jinja2 flask-sqlalchemy

我正在尝试将SQLAlchemy模型传递给View:

class Bandwidth(db.Model):
    __tablename__ = 'bandwidth'
    id = db.Column('id', db.Integer, primary_key=True)
    ping = db.Column('ping', db.Integer)
    download = db.Column('download', db.Float)
    upload = db.Column('upload', db.Float)
    timestamp = db.Column('timestamp', db.DATETIME)

    def __init__(self, ping, download, upload, timestamp):
        self.ping = ping
        self.download = download
        self.upload = upload
        self.timestamp = timestamp

我从db获取数据并通过以下方式将其传递给视图:

list = Bandwidth.query.all()
return render_template('index.html',list=list)

而且最终它在尝试执行时失败了:

{% for item in list %}
   <tr>
     <td>{{ item.timestamp.strftime('%d.%m.%Y %H:%M') }}</td>
     <td>{{ '%s' % item.ping }}</td>
     <td>{{ '%0.2f' % item.download }}</td>
     <td>{{ '%0.2f' % item.upload }}</td>
   </tr>
{% endfor %}

发生的错误是: TypeError:&lt; __ main __。带宽对象位于0x7494c7f0&gt;不是JSON可序列化的

我在哪里弄错了?

1 个答案:

答案 0 :(得分:1)

您可以序列化模型。

class Bandwidth(db.Model):
    __tablename__ = 'bandwidth'
    id = db.Column('id', db.Integer, primary_key=True)
    ping = db.Column('ping', db.Integer)
    download = db.Column('download', db.Float)
    upload = db.Column('upload', db.Float)
    timestamp = db.Column('timestamp', db.DATETIME)

    @property
    def serialize(self):
        return {
            'id': self.id,
            'ping': self.ping,
            ...
        }

from flask import jsonify
list = Bandwidth.query.all()
serialized = [item.serialize for item in list]
return render_template('index.html',list=serialized)