【问题标题】:Flask-SQLAlchemy iterate column values on a single rowFlask-SQLAlchemy 在单行上迭代列值
【发布时间】:2013-06-05 18:30:15
【问题描述】:

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

customer = Customers.query.filter_by(cat_id = page).first()
return render_template('test.html',
    customer = customer
    )

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

在我目前使用的模板中:

{{customer.id}}
{{customer.name}}
{{customer.area}}
etc.

但我想做这样的事情:

{% for item in customer %}
    {{item[column]}}
{% endfor %}

查询可以转换成字典吗?

我已经搜索了所有试图弄清楚这一点但没有运气,这让我认为我可能走错了路。

非常感谢任何建议。


更新:
我认为这是进步。主要变化是在views.py 中,我添加了.__dict__,从我读到的内容可以访问SQLAlchemy 对象的内部__dict__。 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)

views.py

customer = Customers.query.filter_by(cat_id = page).first()
return render_template('test.html',
    customer = customer.__dict__
    )

test.html

{% for key, value in customer.items() %}
    {{ key }} , {{ value }}
{% endfor %}

输出

cust_name , John _sa_instance_state , 
<sqlalchemy.orm.state.InstanceState object at 0x03961D50> id , 1 cat_id , 2 cust_area , England

【问题讨论】:

    标签: python flask flask-sqlalchemy


    【解决方案1】:

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

    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
    )
    

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

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

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2015-02-06
      • 1970-01-01
      • 2021-12-25
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-01
      • 2023-03-17
      相关资源
      最近更新 更多