[FIXED] Referencing values using foreign key on flask sql-alchemy


I have models like this:

class User(db.Model):
    id=db.Column(db.Integer, primary_key=True)

class Post(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    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:

{% for entry in entries %}
       <td> {{ entry.id }} </td>
       <td> {{ entry.title }} </td>
       <td> {{ entry.user_name }} </td>
       <td> {{ entry.user_email }} </td>
{% endfor %}

However, I don’t know 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’test@test.com’,).


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

Answered By – codegeek

Answer Checked By – Mildred Charles (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published