excerpt: Hello, World!* So here I am and welcome to my first blog. Having a personal space on the Internet has been a dream for me for years and I am happy that it fi...
title: "Automatically Build and Deploy Your Site using GitHub Actions and Webhooks"
date: 2022-01-04 20:40:00 +0300
classes: wide
tags: github-actions github-webhooks ci-cd
---
In this post I will explain how you can use GitHub to automate the build and deployment processes that you have. I am going to automate the deployment of this site but you can do whatever you want. Just understanding the basics will be enough.
title: "Conditionally load SQLAlchemy model relationships in FastAPI"
date: 2024-08-04 12:55:00 +0300
date: 2024-08-04 12:55:01 +0300
classes: wide
tags: fastapi sqlalchemy pydantic
---
Suppose you have a FastAPI app responsible for talking with database via sqlalchemy and retrieving data. The sqlalchemy models have some `relationship`s and the job of your app is exposing this database models with or without relationships based on the operation. You can't make use of relationship loading strategies (`'selectin'`, `'joined'` etc.) because FastAPI tries to convert the result to pydantic schemas and pydantic tries to load the relationship even though you don't need it to load for that specific operation. There are three things you can do:
1. Define the loading strategy in your sqlalchemy models and create different pydantic schemas for the same entity including/excluding different fields. (i.e. if you don't need to load `Book.reviews` for specific endpoint, create a new pydantic schema for books without including `reviews`). After that, create different routes for returning correct schema. (`get_books_with_reviews`, `get_books_without_reviews` etc.)
1.*Define the loading strategy in your sqlalchemy models and create different pydantic schemas for the same entity including/excluding different fields. (i.e. if you don't need to load `Book.reviews` for specific endpoint, create a new pydantic schema for books without including `reviews`). After that, create different routes for returning correct schema. (`get_books_with_reviews`, `get_books_without_reviews` etc.)*<br/>
This is the easiest option. Once you decided how each field should be loaded, you only need to create different pydantic schema for loading different fields. The downside is that you will have a lot of schemas and maintaining them will be hard.
2. Create a pydantic schema with all fields and declare some fields as nullable. Do not load anything by default in sqlalchemy models (`lazy='noload'`). Create different routes returning the same schema but inside the routes, manually edit the `query.options` to load different fields.
2.*Create a pydantic schema with all fields and declare some fields as nullable. Do not load anything by default in sqlalchemy models (`lazy='noload'`). Create different routes returning the same schema but inside the routes, manually edit the `query.options` to load different fields.*<br/>
This is what we were doing in our project. Only implementing the routes that we need 90% of the time was working fine for us. If we need more data, we were doing a second request to our API and merging the results. This becomes tedious after some time which is why we decided to move away from it.
3. Somehow get the loading options as input from users of your API and return what is requested.
3.*Somehow get the loading options as input from users of your API and return what is requested.*<br/>
That's it! If such endpoint exists all our problems would be solved. In this post, we will implement that!

@ -178,17 +178,37 @@ async def get_authors():
asyncdefget_reviews():
session=Session(engine)
query=session.query(Review)
result=query.all()
returnresult
returnquery.all()
```
Let's test to see if we are at the same point. Run `uvicorn app:app --reload` then go to `http://127.0.0.1:8000/docs`. If everything went correctly you should see two authors returned when you perform a GET request on `/authors` endpoint.
Let's test to see if we are at the same point. Run `uvicorn app:app --reload` then perform a GET request for `/authors` endpoint. You should see two authors returned:
```sh
❯ curl -X 'GET'\
'http://127.0.0.1:8000/authors'\
-H 'accept: application/json'| jq
[
{
"id": 1,
"name": "Author 1",
"books": [],
"awards": []
},
{
"id": 2,
"name": "Author 2",
"books": [],
"awards": []
}
]
```
Now, let's start implementing what's required to load different fields based on user input. First of all, we need to have a way to determine the relationships of our database models. Then we will use these relationships to generate pydantic schemas which represents loading options. We will then use these schemas as input to our endpoint and inside our endpoint, we will load required fields.
1. Define a `RelationshipLoader` class in `models.py`.
```python
fromtypingimportAny
fromsqlalchemy.inspectionimportinspect
@ -223,7 +243,7 @@ class RelationshipLoader:
load_strategy=(# if it is a one to one or many to one relationship we are loading it with selectinload strategy, else joinedload
{"selectinload":[getattr(cls,rel.key)]}
ifrel.direction.namein["MANYTOONE","ONETOMANY"]
else{"joinedload":getattr(cls,rel.key)}
else{"joinedload":[getattr(cls,rel.key)]}
)
relationships[rel.key]=load_strategy
@ -234,12 +254,9 @@ class RelationshipLoader:
[*exclude_classes,cls]# excluding the current class because we don't want bidirectional relationships to create infinite loop
# To modify the layout, see https://jekyllrb.com/docs/themes/#overriding-theme-defaults
layout: home
classes: wide
---
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.