question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] SQL related tables and corresponding nested pydantic models in async

See original GitHub issue

Really impressed with FastAPI so far… I have search docs github, tickets and googled the issue described below.

Description

How best to work with related tables and corresponding nested pydantic models whilst persisting data in a relational database in an async application?

Additional context

I have been attempting to extend the example in the docs https://fastapi.tiangolo.com/advanced/async-sql-databases/ which relies on https://github.com/encode/databases

Using three test pydantic models as an example:

class UserModel(BaseModel):
    id: int
    title: str = Field(..., min_length=2, max_length=50)
    firstname: str = Field(..., min_length=1, max_length=50)
    firstname: str = Field(..., min_length=1, max_length=50)
    username: str = Field(..., min_length=3, max_length=50)
    email: str = Field(..., min_length=3, max_length=50)
    favourite_book: int = Field(...)

class FavouriteBook(BaseModel):
    id: int
    title: str = Field(...)
    author: str = Field(...)


class ExtendedUser(BaseModel):
    id: int
    title: str = Field(..., min_length=2, max_length=50)
    firstname: str = Field(..., min_length=1, max_length=50)
    firstname: str = Field(..., min_length=1, max_length=50)
    username: str = Field(..., min_length=3, max_length=50)
    email: str = Field(..., min_length=3, max_length=50)
    favourite_book: FavouriteBook

the route would ideally be along the lines of…

@router.get("/extended", response_model=List[ExtendedUser])
async def list():
    query =  **sqlAlchemy/databases call that works**
    return database.fetch_all(query=query)

How can a user create a route that returns the nested ExtendedUser from the database without resorting to performing two queries? An SQL join is a standard way to do this with a single query. However, this does not work with SQLAlchemy core as the two tables contain ‘id’ and ‘title’ columns.
It is possible to work with SQLAlchemy orm - but not in an async way as far as I know. (async is my reason for using FastAPI ). I could rename the columns to something unique ( but to rename ‘id’ column seems like poor database design to me).

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:19 (9 by maintainers)

github_iconTop GitHub Comments

2reactions
tiangolocommented, Jun 4, 2020

Yep, I know. We still don’t have a solution for that. I have been thinking about creating a small layer on top of SQLAlchemy mixing SQLAlchemy and Pydantic… but we’ll see 😅

1reaction
leonhcommented, Apr 13, 2020

Thanks for the advice and continued work on FastAPI. I like the performance and syntax of PonyORM but it seems to fallen into a period of sporadic maintenance which is a cause for concern. My understanding was that as it was built in a way that would allow it to possibly be async friendly in the future even if it wasn’t there right now. I hope the use of contextvars for asyc’ing PonyOrm works. I think the developers did a really good job on it when it was being built a few years ago, but maybe their priorities have moved in a different direction since then.

Planning to give Tortoise ORM a test run at some point, seeing as its been created to work well with FastAPI.

Side thought: The developer experience of so many similar but different typing systems in my code. Dataclasses, ORM models, Pydantic validation, OpenApi schema, JS Form libraries, or typescript, state management models for React. It gets quite repetitive from end to end if no type system is designated as the canonical form within a web stack.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Nested Pydantic Model return error with FastAPI
I try to return a list of records based on my Pydantic model. Here is the SQLAlchemy Metadata : from sqlalchemy import MetaData,...
Read more >
Many-To-Many Relationships In FastAPI
In this tutorial, I cover multiple strategies for handling many-to-many relationships using FastAPI with SQLAlchemy and pydantic.
Read more >
SQL (Relational) Databases - FastAPI
Create model attributes/columns¶. Now create all the model (class) attributes. Each of these attributes represents a column in its corresponding database table.
Read more >
SQLModel: SQL DBs based on Python type hints. The ...
Each model is both a Pydantic and SQLAlchemy model, ... nested models (like nested Pydantic models) to read the table model using .from_orm....
Read more >
tiangolo/fastapi - Gitter
I need to know how to get nested models, while performing get method from a sql query. The sql query is correct, it...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found