Not found
Not found

Reputation: 71

how to return only one column from database in pydantic model as a list?

I have a simple database relationship that stores which user liked which post. But in liked attribute, it's returning a list of dictionaries that contains post_id but I want to return the list of app_ids.

Here is my pydantic model:

class PostLiked(BaseModel):
    post_id: str

    class Config:
        orm_mode = True

class ShowUser(BaseModel):
    public_id: str
    name: str
    username: str
    email: str
    number_of_apps: int
    is_developer_account: bool
    profile_image_url: Any or str
    created_account_on: Any or str
    liked: List[AppLiked]

    class Config:
        orm_mode = True```

Here is what it is returning:

{
  "public_id": "0bdf790b",
  "name": "Tazim Rahbar",
  "username": "tazim404",
  "email": "[email protected]",
  "number_of_post": 1,
  "is_developer_account": true,
  "profile_image_url": "https://picnicss.com/img/basket.png",
  "created_account_on": "2021-08-15T18:49:35.367674",
  "liked": [
    {
      "post_id": "70a31f76"
    },
    {
      "post_id": "2674a446"
    },
    {
      "post_id": "dd977cc8"
    }
  ]
}

But I want like:

{
  "public_id": "0bdf790b",
  "name": "Tazim Rahbar",
  "username": "tazim404",
  "email": "[email protected]",
  "number_of_posts": 1,
  "is_developer_account": true,
  "profile_image_url": "https://picnicss.com/img/basket.png",
  "created_account_on": "2021-08-15T18:49:35.367674",
  "liked": ["70a31f76", "2674a446", "dd977cc8"]
  
}

Can you please help me out?

Upvotes: 7

Views: 913

Answers (1)

Daniel Katzan
Daniel Katzan

Reputation: 564

you can use pydantic [GetterDict][1] https://pydantic-docs.helpmanual.io/usage/models/#data-binding

something like

class UserGetter(pydantic.utils.GetterDict):
    def get(self, key: str, default: Any) -> Any:
        if key == "liked":
            # Use self._obj, which is the orm model to build the list of apps_ids and return that
            pass
        return super().get(key, default)

class PostLiked(BaseModel):
    post_id: str

    class Config:
        orm_mode = True

class ShowUser(BaseModel):
    public_id: str
    name: str
    username: str
    email: str
    number_of_apps: int
    is_developer_account: bool
    profile_image_url: Any or str
    created_account_on: Any or str
    liked: List[AppLiked]

    class Config:
        orm_mode = True
        getter_dict = UserGetter

Upvotes: 1

Related Questions