CRUD via SQLAlchemy
Get All
We will have to import the
database.pyfile and themodels.pyfile
from . import models
from app.database import engine, get_dbNext we will create the function with that calls the
get_dbdependency and creates the query
@app.get("/sqlalchemy")
# We are saving the dependency and session in a variable (db)
def test_post(db: Session = Depends(get_db)):
# We call that variable
# Set to query
# Add the class name from the models.py Table
# Fetch all rows with .all()
posts = db.query(models.Post).all()
return { "data": posts }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
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_queryvariableThen 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_schemathat already is passed inCommits this to the database
To return it to the user, we just run another query
Last updated