Flask SQLAlchemy simple queries
Posted on
by Kevin FoongIn this post we will explore some simple SQLAlchemy statements and compare them to their SQL equivalents. This post is just on using Flask SQLAlchemy to query your database. If you want to know how to model your database please see my other post here. Let's get started!
Let's say we have two tables UserDetails
and Country
in a one to many relationship towards Country
. That is one UserDetails
can only have one Country
. But one Country
can have many UserDetails
. Our models look like this.
UserDetails
class UserDetails(db.Model):
__tablename__ = 'user_details'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
first_name = db.Column(db.String(50), nullable=False)
last_name = db.Column(db.String(50), nullable=False)
gender_id = db.Column(db.Integer, db.ForeignKey('gender.id'), nullable=False)
dob = db.Column(db.String(10), nullable=False)
country_id = db.Column(db.Integer, db.ForeignKey('country.id'), nullable=False)
state = db.Column(db.String(30), nullable=False)
city = db.Column(db.String(30), nullable=False)
def __repr__(self):
return '<UserDetails {}>'.format(self.first_name)
Read more ...
Tags: flask flask-sqlalchemy database