[Python] i can not find the solution with this task (fastapi and sql)

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    @router.get("/", response_model=list[sh.PostResponse]) def ger_posts():
    curr.execute("""
    SELECT *
    FROM posts
    JOIN users ON users.id = posts.user_id

    """)
    posts = curr.fetchall()
    conn.commit()
    return posts


    class UserResponse(BaseModel):
    id: int
    email: EmailStr
    created_at: datetime

    class PostResponse(PostBase):
    id: int
    created_at: datetime
    user_id: int
    owner: UserResponse


    can you help me to solve the error. there i want it to return proper json where will be information about post and user (owner).

    for better understanding what i want to do, my friend used orm and added this to his database from python to get the exact same result i want:

    owner = relationship("user")


    but i don't use orm because i use psycopg2. is it possible to solve this problem effectively without orm, or am i better start using it soon? is it okay to work with psycopg2 with orm? how to solve this specific task?

    kind of result i need:

    [
    {
    "title": "test 1",
    "content": "testing",
    "published": true,
    "id": 1,
    "created_at": "2025-03-01T10:09:55.174834+04:00",
    "user_id": 2,
    "owner":{
    "id": 2,
    "email": testemail@gmail.com,
    "created_at": "some timestamp e.g 2025-03-01T10:09:55.174834+04:00"
    }
    }
    ]

    Continue reading...

Compartilhe esta Página