1

我正在使用 for 循环输出单个数据库行的列和值。这一切正常,但有几个问题。列名不适合在浏览器中输出,所以我正在寻找一种关联别名的方法(不确定这是正确的术语)

例如。列名:

cust_name
cust_area

期望的输出:

Customer name
Customer area

模型.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)

视图.py

customer = Customers.query.filter_by(cat_id = page).first()
test_dict = dict((col, getattr(test, col)) for col in test.__table__.columns.keys())
return render_template('test.html',
    customer = test_dict
    )

测试.html

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

谢谢!

4

1 回答 1

1

使用info字典:

class Customers(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    cust_name = db.Column(db.String(64), info={'name': 'Customer name'})
    cust_area = db.Column(db.String(64), info={'name': 'Customer area'})
    cat_id = db.Column(db.Integer(8), index=True)

然后您可以遍历如下列:

customer = Customers.query.filter_by(cat_id=page).first()
data = dict((c.info.get('name', c.name), getattr(customer, c.name))
            for c in customer.__table__.c)
# Or using dict comprehension syntax (Python 2.7+).
data = {c.info.get('name', c.name): getattr(customer, c.name)
        for c in customer.__table__.c}
于 2013-06-08T08:46:42.943 回答