Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing values using foreign key on flask sql-alchemy

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?

like image 707
Wohoo Summer Avatar asked Oct 16 '13 15:10

Wohoo Summer


1 Answers

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
like image 86
codegeek Avatar answered Oct 11 '22 17:10

codegeek