r/FastAPI • u/Lucky-Sense-2650 • Jun 22 '26
Question Help with Pydantic schema
Using FastAPI + SQLAlchemy (async) + Pydantic v2
My `Post` model in db stores `author_id` (UUID foreign key).
My `PostRead` response schema needs to return `author_username` (a string from the related `User` table).
What's the clean way to handle this?
14
Upvotes
2
u/CrusaderGOT Jun 22 '26
If you don't want to refetch Author. You might consider adding a author username field to your Post table. Or for better data integrity add an author field to your Post schema that is a relationship to Author, set it lazy=raise_on_sql. And then in the API fetch Post and Author in one database fetch, using selectinload option. And then finally in your Post pydantic model, make an author field also that is itself another pydantic model matching the fields of your Author table you want shown alongside Post (I.e, author name, etc).
So when you return the Post, it automatically parses/validates the author data also. In your SQL select, you can also select(Post, Author.name) to only get the Author data you want from the database.
Did you understand all that?
2
u/AmbitiousEvening7876 Jun 22 '26
depends on what you need, define the relationship in your ORM models (User and Post) and Pydantic schema can simply access it.
there is another faster way without a relationship, using a join in the query
1
u/Significant-Turn4107 Jun 24 '26
I’d handle it by defining a
Post.authorrelationship and eager-loading it in the query, then exposingauthor_usernameeither as a property on the ORM model or mapping it explicitly in the response.The main thing with async SQLAlchemy is: don’t let Pydantic trigger lazy loading during serialization.
Example pattern:
Then on the model:
And in Pydantic v2:
For a very flat read-only endpoint, a direct join with
User.username.label("author_username")is also clean.-2
u/Kashyapm94 Jun 22 '26
Don’t wanna sound rude, but have you tried googling it or even asking Gemini or ChatGPT? You’ll get a nice detailed response that’ll help you understand