如果 pydantic 模型定义了别名,如何使用“from_orm”?

Min*_*eet 6 orm sqlalchemy pydantic

虽然 pydantic 的 ORM 模式记录在此处,但遗憾的是没有使用别名的文档。

from_orm如果pydantic模型定义了别名如何使用?

如果存在别名,工厂似乎from_orm会忘记所有非别名。- 请参阅下面的错误消息和相应的代码。这是一个错误还是一个功能?

下面的代码片段意外失败并出现验证错误:

pydantic.error_wrappers.ValidationError:SimpleModel
ThreeWordsId
字段需要 1 个验证错误(type=value_error.missing)

from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel, Field

Base = declarative_base()

class SimpleOrm(Base):
    __tablename__ = 'simples'
    three_words_id = Column(String, primary_key=True)

class SimpleModel(BaseModel):
    three_words_id: str = Field(..., alias="threeWordsId")

    class Config:
        orm_mode=True

simple_orm = SimpleOrm(three_words_id='abc')
simple_oops = SimpleModel.from_orm(simple_orm)
Run Code Online (Sandbox Code Playgroud)

小智 11

在配置中使用allow_population_by_field_name = True

喜欢

from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel, Field

Base = declarative_base()


class SimpleOrm(Base):
    __tablename__ = 'simples'
    three_words_id = Column(String, primary_key=True)


class SimpleModel(BaseModel):
    three_words_id: str = Field(..., alias="threeWordsId")

    class Config:
        orm_mode = True
        allow_population_by_field_name = True
        # allow_population_by_alias = True # in case pydantic.version.VERSION < 1.0


simple_orm = SimpleOrm(three_words_id='abc')
simple_oops = SimpleModel.from_orm(simple_orm)

print(simple_oops.json())  # {"three_words_id": "abc"}
print(simple_oops.json(by_alias=True))  # {"threeWordsId": "abc"}


from fastapi import FastAPI

app = FastAPI()


@app.get("/model", response_model=SimpleModel)
def get_model():
    # results in {"threeWordsId":"abc"}
    return SimpleOrm(three_words_id='abc')

Run Code Online (Sandbox Code Playgroud)