gpt4 book ai didi

python - Flask-sqlalchemy 浏览器输出的列别名

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:23 24 4
gpt4 key购买 nike

我使用 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)

View .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 %}

谢谢!

最佳答案

使用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}

关于python - Flask-sqlalchemy 浏览器输出的列别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com