fastapipydanticsqlmodelpydantic-v2

Cannot dump SQLModel entity


I've got an SQLModel entity

# model Permission
class Permission(SQLModel, table=True):
    __tablename__ = 'permission'

    id: int = Field(primary_key=True)
    name: str = Field(unique=True)

    permission_roles: list['RolePermissionAssignment'] = Relationship(back_populates='permission')

Which I want to map to a pydantic model, to maintain a level of abstraction and separation, as well as removing some of the data - the following model is used as a response:

# schema Permission
class Permission(BaseModel):
    id: int = Field(..., description='Database ID')
    name: str = Field(..., description='Name of the permission')

In this method, I want to convert the list of model.Permission fetched from the database to schema.Permission. Since both are Pydantic models, it should be sufficient to model_dump -> model_validate, but I'm getting AttributeError: model_dump.

The thing is, Pydantic v2 should be supported from SQLModel v0.0.014. My project uses Pydantic v2.8.2 and SQLModel v0.0.19, so the method, which is introduced (afaik) in pydantic v2 should be included.

I would like to avoid downgrading to pydantic v1 if possible.

Configuring of the models, different parametrisation of the model_validate method, tried using the recommended model_dump


Solution

  • You should use from_attributes=True in model config to be able to build your schema from a db model. I've tested the following code and it seems working:

    class Permission(SQLModel, table=True):
        __tablename__ = 'permission'
    
        id: int = Field(primary_key=True)
        name: str = Field(unique=True)
    
    
    class PermissionSchema(BaseModel):
        model_config = ConfigDict(from_attributes=True)
    
        id: int = Field(..., description='Database ID')
        name: str = Field(..., description='Name of the permission')
    
    
    permission = Permission(id=1, name="Steve")
    PermissionSchema.model_validate(permission)