Referencing values using foreign key on flask sql-alchemy Referencing values using foreign key on flask sql-alchemy sqlite sqlite

Referencing values using foreign key on flask sql-alchemy


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().nameemail = User.query.filter_by(id=post.id).first().email


First of all the solution is to query using the related fields.You can get the user details using the below query:Let us assume that the id in the user model is 1 and user in post model value is 1 i.e(id=1, user=1).

Link post model with user modelYou will have link them with the related fields i.e(User model has id and Post model has user as a foreign key)

import Post #import post model

user = User.query.filter(User.id==Post.user).first()

The below will give first post in post model created by the user

import User #import user model

post = Post.query.filter(Post.user==User.id).first()post.idpost.titleuser.nameuser.email

You can also query to get all posts like below

posts = Post.query.filter(Post.user==User.id).all()