I just recently got into web development using flask and sql-alchemy. Everything was working fine until I had to access values using Foreign keys. I have models like this:
class User(db.Model):
_tablename='user'
id=db.Column(db.Integer, primary_key=True)
name=db.Column(db.String)
email=db.Column(db.String)
class Post(db.Model):
_tablename='post'
id=db.Column(db.Integer, primary_key=True)
title=db.Column(db.String)
user=db.Column(db.Integer, db.ForeignKey('user.id'))
I would like to display the list of all posts on a web page, with something like this in html file:
{% for entry in entries %}
<tr>
<td> {{ entry.id }} </td>
<td> {{ entry.title }} </td>
<td> {{ entry.user_name }} </td>
<td> {{ entry.user_email }} </td>
{% endfor %}
However, I am not sure how to access the user and email from the user table, using the user.id foreign key. I tried
posts = Post.query.all()
for post in posts:
post.user_name = User.query.filter_by(id=post.id).first()
return render_template('post.html', entries=posts)
But then instead of returning just the name and email, like the title from post, it is returning something like (u'User A',) and (u'[email protected]',). And I can't think of any other way. Can anyone help me with it?
You are almolst there but this code below does not actually return the username. It returns the entire user object:
User.query.filter_by(id=post.id).first() # Does Not return user_name but returns the user object
So I would call it something like:
userobj = User.query.filter_by(id=post.id).first()
Then you can retrieve the username,email as:
if userobj is not None: # Make sure user exists
username = userobj.name
email = userobj.email
As a shortcut, you can also do:
username = User.query.filter_by(id=post.id).first().name
email = User.query.filter_by(id=post.id).first().email
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With