Flask-sqlalchemy column alias for browser output

拥有回忆 提交于 2019-12-13 00:55:06

问题


I'm using a for loop to output the columns and values of a single database row. This is all working but there are a couple of issues. The column names aren't suitable to output in the browser so I'm looking for a way to associate an alias (not sure this is the correct term)

eg. column names:

cust_name
cust_area

Desired output:

Customer name
Customer area

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()
test_dict = dict((col, getattr(test, col)) for col in test.__table__.columns.keys())
return render_template('test.html',
    customer = test_dict
    )

test.html

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

Thanks!


回答1:


Use info dictionary:

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)

Then you could iterate through columns like following:

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}


来源:https://stackoverflow.com/questions/16985970/flask-sqlalchemy-column-alias-for-browser-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!