translate SQL query to flask-sqlalchemy statements
<p>I am changing my old SQL implementations of a web app to flask-alchemy and having some difficulties about the correspondence.</p>

<p>The old code looks like this. It does the name query about some properties and returns a csv style text. </p>

<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
base_query = '''SELECT id, bbs_id, city, state, 
                     latitude, longitude FROM mytable'''
conn = sqlite3.connect(path.join(ROOT,'db.sqlite')) 
c = conn.execute(base_query+'WHERE name=?', (name,))
results = c.fetchall()
conn.close()
rows = [','.join(map(str, row)) for row in results]
return header + rows
</code></pre>

<p>The new code</p>

<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
cols = ['id', 'bbs_id', 'city', 'state', 'latitude', 'longitude'] 
users = User.query.filter_by(name=name).all()
rows = ''
for user in users:
    rows += ','.join([user.id, user.bbs_id, user.city, user.state, user.latitude, user.longitude]) + '\n'
return header + rows
</code></pre>

<p>I am not happy with the new code since it's so verbose. </p>

<ul>
<li>Is there a way to select only the ones in <code>cols</code> instead of query all columns and then pick the needed columns? </li>
<li>If not, is it possible to write the <code>','.join()</code> more succinctly? It seems <code>user['id']</code> does not work and I have to do <code>user.id</code>.</li>
</ul>

<p>If you just want a result set as before, you can do:</p>

<pre><code>results = db.session.query(*(getattr(User, col) for col in cols)).filter_by(...)
</code></pre>

<p>and then you can use <code>results</code> as you did before.</p>

<p>If, OTOH, you want to use the ORM, you can use <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_columns.html#sqlalchemy.orm.load_only" rel="nofollow"><code>load_only</code></a>:</p>

<pre><code>users = User.query.options(*(load_only(col) for col in cols)).filter_by(...)
rows = "".join(",".join(*(getattr(u, col) for col in cols)) + "\n" for u in users)
</code></pre>

python sql sqlalchemy flask-sqlalchemy