bobwal
bobwal

Reputation: 542

Flask-sqlalchemy column alias for browser output

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!

Upvotes: 1

Views: 1149

Answers (1)

Audrius Kažukauskas
Audrius Kažukauskas

Reputation: 13543

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}

Upvotes: 1

Related Questions