Search code examples
pythonfastapipydanticsqlmodel

How to change a pydantic list of objects into list of strings?


I'm using SQLModel for an API.

I want the object to be like this:

class Post(SQLModel):
    id: int
    categories: list[str]  # category.name

instead of nested objects:

class Post(SQLModel):
    id: int
    categories: list[Category]

Do I have to change the serialization function or is there a way to do this automatically?


Solution

  • As far as I understood Post is your db model. I would highly recommend to separate you db model (should reflect the database structure) from dto (should be used for comfortable data transfer between application components)

    class PostDTO(pydantic.BaseModel):
        id: int
        categories: list[str]
    
        @classmethod
        def from_db_model(cls, model: Post) -> "PostDTO":
            """Build Post DTO based on db model."""
    
            return cls(
                id=model.id,
                categories=[category.name for category in model.categories]
            )
       
    post = Post(...)
    post_dto = PostDTO.from_db_model(model=post)
    
    

    Don't be afraid to create an extra object if it makes your code more scalable, readable and logical!