I'm creating social media app with FASTAPI framework. I'm joining likes using sqlalchemy.orm into post table. The data I get is correct but I want everything to be under post object rather then having post/likes object
Here are the models
class UserBase(BaseModel):
id: int
email: EmailStr
class Config:
orm_mode = True
class PostBase(BaseModel):
title: str
description: str
class BasePostResponse(PostBase):
id: int
created_at: datetime
user: UserBase
class Config:
orm_mode = True
class PostResponse(BaseModel):
SocialPost: BasePostResponse = Field(alias="data")
likes: int
class Config:
orm_mode = True
allow_population_by_field_name = True
Here is how I join and get all the posts
@router.get("/all", response_model= List[socialMedia.PostResponse])
def get_posts(db: Session = Depends(get_db), per_page: int = 50, page: int = 1, search: Optional[str] = ""):
posts = db.query(models.SocialPost, func.count(models.SocialLikes.post_id).label('likes')).join(models.SocialLikes, models.SocialLikes.post_id == models.SocialPost.id, isouter= True).group_by(models.SocialPost.id).filter(models.SocialPost.title.contains(search)).limit(per_page).offset(per_page * (page - 1)).all()
return posts
The response I get
[
{
"data": {
"title": "First post",
"description": "First Desc",
"id": 2,
"created_at": "2022-09-19T21:47:45.660685 02:00",
"user": {
"id": 1,
"email": "[email protected]"
}
},
"likes": 0
},
...
]
And I would like to just get
[
{
"title": "First post",
"description": "First Desc",
"id": 2,
"created_at": "2022-09-19T21:47:45.660685 02:00",
"user": {
"id": 1,
"email": "[email protected]"
},
"likes": 0
},
...
]
CodePudding user response:
I found a fix.
In the models, under post table I used likes =column_property(select([func.count ...
So, in the schemas I just added the likes property to original PostResponse and it returns the response I desired
Leaving this in case anyone else struggles :)