如何返回只有一个列从数据库中的pydantic模型作为一个列表?



我有一个简单的数据库关系,它存储哪个用户喜欢哪个帖子。但在like属性中,它返回包含post_id的字典列表但我想返回app_ids的列表

这是我的pydantic模型:

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```

返回的结果如下:

{
"public_id": "0bdf790b",
"name": "Tazim Rahbar",
"username": "tazim404",
"email": "rahbartazim@gmail.com",
"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"
}
]
}

但是我想要:

{
"public_id": "0bdf790b",
"name": "Tazim Rahbar",
"username": "tazim404",
"email": "rahbartazim@gmail.com",
"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"]

}

你能帮帮我吗?

可以使用pydantic[GetterDict][1]https://pydantic-docs.helpmanual.io/usage/models/#data-binding

之类的
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

最新更新