CRUD via SQLAlchemy
Get All
We will have to import the
database.py
file and themodels.py
file
Next we will create the function with that calls the
get_db
dependency and creates the query
Note: Syntax for all queries is:
db variable
query to interrogate
models.<CLASS_NAME> - table that we want to use
.add() - Fetches all rows
Get by ID
We will fetch the post by ID by using the query and filtering for the ID in the models that is equal to the ID passed in
Note: If you know that you only have a single post with said ID, use the method .first()
instead of .all()
This is more efficient as
.all()
will look further through all posts, even tho it has found the post with the ID specifiedMeaning that it uses resources that it doesn't need
Create
We're basically doing the same thing as RAW SQL but we are passing in the variables directly
Delete
The first part of the query stays the same as the Get ID one
We do call the
.first()
method to check if there is no IDIf there isn't it will raise an exception
Outside the IF statement we will delete the post with the ID
Then we have to commit the changes to the database
Update
We are saving the query in the
post_query
variableThen we are getting the first post
If that post does not exist, it raises an error
If it does it updates the database entry with the
post_schema
that already is passed inCommits this to the database
To return it to the user, we just run another query
Last updated