zhanymkanov / fastapi-best-practices

FastAPI Best Practices and Conventions we used at our startup
9.38k stars 700 forks source link

Database.py file was not presented in the documentation #50

Closed WickedSs closed 4 months ago

WickedSs commented 4 months ago

I'd be very grateful if you could provide us with the content of database.py because I couldn't understand this part:

from src.database import database, posts, profiles, post_review, products

async def get_posts(
    creator_id: UUID4, *, limit: int = 10, offset: int = 0
) -> list[dict[str, Any]]: 
    select_query = (
        select(
            (
                posts.c.id,
                posts.c.slug,
                posts.c.title,
                func.json_build_object(
                   text("'id', profiles.id"),
                   text("'first_name', profiles.first_name"),
                   text("'last_name', profiles.last_name"),
                   text("'username', profiles.username"),
                ).label("creator"),
            )
        )
        .select_from(posts.join(profiles, posts.c.owner_id == profiles.c.id))
        .where(posts.c.owner_id == creator_id)
        .limit(limit)
        .offset(offset)
        .group_by(
            posts.c.id,
            posts.c.type,
            posts.c.slug,
            posts.c.title,
            profiles.c.id,
            profiles.c.first_name,
            profiles.c.last_name,
            profiles.c.username,
            profiles.c.avatar,
        )
        .order_by(
            desc(coalesce(posts.c.updated_at, posts.c.published_at, posts.c.created_at))
        )
    )

    return await database.fetch_all(select_query)

thank you so much

zhanymkanov commented 4 months ago

Mostly, it looks like this with bunch of tables

WickedSs commented 4 months ago

The best fastapi app structure I've ever seen, easy to learn and understand, thank you