Home > OS >  How to Exclude a column in a row of data in sqlalchemy and fastapi
How to Exclude a column in a row of data in sqlalchemy and fastapi

Time:12-05

I am trying to load only AuthUser.id and AuthUser.username from the below result

statement = select(func.count(UserCountry.id).label("uid"),
                    AuthUser.id,AuthUser.username).\
                    join(CountryTool, CountryTool.id == UserCountry.country_tool_id).\
                    join(Country, Country.id == CountryTool.country_id).\
                    join(Tool, Tool.id == CountryTool.tool_id).\
                    join(AuthUser, AuthUser.id == UserCountry.user_id).\
                    where(CountryTool.id == country_tool_id).\
                    group_by(AuthUser.id,AuthUser.username)

current json response is

{
    "uid": 1,
    "id": 1,
    "username": "ross"
},
{
    "uid": 1,
    "id": 2,
    "username": "harvey"
}

response that I need is

{
    "id": 1,
    "username": "ross"
},
{
    "id": 2,
    "username": "harvey"
}

CodePudding user response:

This might help

response = []
for res in results:
    response.append({
        "id": res[1],
        "username": res[2]
    })

CodePudding user response:

This will works for your intention.

from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class Item(BaseModel):
    uid: str
    id: int
    name: str

    class Config:
        orm_mode = True
       

statement = ... 

@app.get("/items/{item_id}", response_model=list[Item], response_model_exclude=["uid"])
async def read_item(item_id: str):
    return statement
  • Related