[Python] How to create pydantic model with different names of filed?

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have pydantic model of table and another one for create like:

    class Users(SQLModel, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True)
    user: str = Field(index=True)
    new_name: str = Field(index=True, alias="old_name")
    description: str | None = Field(default=None, nullable=True)


    class UserCreate(SQLModel):
    user: str = Field()
    new_name: str = Field(alias="old_name")
    description: str | None = Field(default=None)


    and api like:

    @router.post("/", response_model=Response, status_code=201)
    async def add_dataset(
    datasets: list[UserCreate],
    session: AsyncDbSession,
    ) -> Response:
    """Add a new dataset to the database."""
    print(f"Adding new dataset: {datasets}")
    for dataset in datasets:
    await create_dataset(session, dataset, autocommit=False)
    await session.commit()
    return Response()


    I need that user can send data with both column name "new_name" and "old_name".

    [
    {
    "user": "Tom",
    "old_name": "sssss",
    "description": "data engineer"
    }
    ]


    I try to write alias, but get 422 from api with response body

    {
    "detail": [
    {
    "type": "missing",
    "loc": [
    "body",
    0,
    "new_name"
    ],
    "msg": "Field required",
    "input": {
    "user": "Tom",
    "old_name": "sssss",
    "description": "data engineer",
    }
    }
    ]
    }


    Also I try to used validation_alias, but it an unexpected keyword argument. And argument response_model_by_alias for api, and it gave nothing

    Pydantic 2.10.5

    pydantic-core 2.27.2

    pydantic-settings 2.7.1

    Continue reading...

Compartilhe esta Página