04 - Modeling the Models
In this module we will define our database models and schemas
Last updated
Was this helpful?
In this module we will define our database models and schemas
Last updated
Was this helpful?
Flask-SQLAlchemy provides a nice, easy to use, high level, ORM (object relational mapper). ORM's allow us to easily manipulate our database, with tiny bits of code. To do this, we use something called migrations
. More on these later.
We are also going to add Bcrypt
. Bcrypt is a nice encryption library that will help us with hashing and verifying passwords
Open up the file models/__init__.py
and add the following code. When we add to an __init__
, the entire package (directory) will be able to access from here
This will allow us to bind our models to SQLAlchemy's Model
and Column
objects.
Open up models/user.py
and add the following code
This is a lot to understand what's going on all at once. So, let's break it down step by step.
__tablename__
: This variable will tell sqlalchemy what to call the table when it migrates
line 10 - 15 : These class attributes define what will go into the table and how the columns will be represented
__init__
: This is just a constructor, it will handle creating our objects before we persist data to the database
save/update/delete
: These methods perform the equivalent actions to an entry to the database. Notice that in the update
method, we never explicitly replace the actual instance attributes. This is still fine, because SQLAlchemy will ONLY commit attributes that are listed as db.Column
get_one_user/get_all_users
: These methods are self explanatory however they are static methods. Think of them as not being tied to an instance and have an overarching view on the database
repr
: Just in case we want to stringify the instances
generate_hash/check_hash
: We also have a couple of helper methods that incorporate bcrypt. These are mostly just abstraction steps so we don't need the dependency throughout the entire project.
blogposts
: This is navigational property. This just tells SQLAlchemy that there is a connection between these two models, but we haven't built out the blog post model yet. This is called coding with intent. We intend to implement it, it's just not there yet. Let's jump into it now
Add the following to models/blog_post.py
Take note of the owner_id
on line 10 in the above snippet. This is our foreign key that links us to the user
model, specifically the users primary key. This will aid us when we start creating our routes that are responsible for deleting and editing the blog posts. Essentially, we don't want other users to edit, or even delete, someone else's post