Flask-SQLAlchemy在单行上迭代列值

bob*_*wal 4 python flask flask-sqlalchemy

我是Flask和Python的新手,所以请提前道歉.我正在使用Flask-SQLAlchemy返回数据库行,这一切都正常:

customer = Customers.query.filter_by(cat_id = page).first()
return render_template('test.html',
    customer = customer
    )
Run Code Online (Sandbox Code Playgroud)

我的问题是我试图弄清楚如何使用循环在我的jinja模板中显示此行的列值.这是解决此问题的最佳方法吗?我得到了"对象不可迭代"的错误,我有点理解,但我不知道如何解决它.

在我目前正在使用的模板中:

{{customer.id}}
{{customer.name}}
{{customer.area}}
etc.
Run Code Online (Sandbox Code Playgroud)

但我想做这样的事情:

{% for item in customer %}
    {{item[column]}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

查询可以转换为字典吗?

我一直在搜索,试图弄清楚没有运气,这让我觉得我可能走错了路.

任何建议都非常感谢.


更新:
我认为这是进步.主要的变化是在views.py中,我已经添加了.__dict__一些来自我读过__dict__的内容的SQLAlchemy对象.for模板循环现在输出列值,但它也输出许多其他不需要的东西.反正有没有清理它?

models.py

class Customers(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    cust_name = db.Column(db.String(64))
    cust_area = db.Column(db.String(64))
    cat_id = db.Column(db.Integer(8), index = True)
Run Code Online (Sandbox Code Playgroud)

views.py

customer = Customers.query.filter_by(cat_id = page).first()
return render_template('test.html',
    customer = customer.__dict__
    )
Run Code Online (Sandbox Code Playgroud)

的test.html

{% for key, value in customer.items() %}
    {{ key }} , {{ value }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

产量

cust_name , John _sa_instance_state , 
<sqlalchemy.orm.state.InstanceState object at 0x03961D50> id , 1 cat_id , 2 cust_area , England
Run Code Online (Sandbox Code Playgroud)

cod*_*eek 6

首先在您的视图中将客户行转换为字典.

customer = Customers.query.filter_by(cat_id = page).first()
customer_dict = dict((col, getattr(customer, col)) for col in customer.__table__.columns.keys())
return render_template('test.html',
customer_dict = customer_dict
)
Run Code Online (Sandbox Code Playgroud)

您可以在customer_dict行上使用iteritems().

{% for key, value in customer_dict.iteritems() %}

   {{ key }} , {{ value }}

{% endfor %}  
Run Code Online (Sandbox Code Playgroud)