python - How to create pydantic model with different names of filed? - Stack Overflow

I have pydantic model of table and another one for create like:class Users(SQLModel, table=True):id: U

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 sessionmit()
    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

Python 3.12.7

Pydantic 2.10.5

pydantic-core 2.27.2

pydantic-settings 2.7.1

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 sessionmit()
    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

Python 3.12.7

Pydantic 2.10.5

pydantic-core 2.27.2

pydantic-settings 2.7.1

Share Improve this question edited Mar 24 at 5:04 yuoggy asked Mar 21 at 12:41 yuoggyyuoggy 1472 silver badges14 bronze badges 2
  • Well you can define multiple validation_alias but what you win from that? You can't differentiate afterwards, if it was send through old_name or new_name and I guess, thats an important information for you. – lord_haffi Commented Mar 21 at 15:00
  • I need it because of potential breaking changes and I can't pass validation_alias cause get an error unexpected keyword argument. – yuoggy Commented Mar 24 at 4:46
Add a comment  | 

1 Answer 1

Reset to default 0

Seems

from pydantic import AliasChoices, BaseModel
..
Field(validation_alias=AliasChoices("old_name", "new_name"))

solve it or

from sqlmodel import Field, SQLModel
..
Field(schema_extra={"validation_alias":AliasChoices("metric_group_id", "project_name")})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744353308a4570102.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信