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

时间:2020-02-06 14:55:45

标签: orm sqlalchemy pydantic

尽管here记录了Pydantic的ORM模式,但遗憾的是,没有有关别名使用的文档。

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

如果存在别名,看来from_orm工厂会忘记所有非别名。 -请参阅以下错误消息和相应的代码。那是错误还是功能?

以下代码段意外失败,并显示验证错误:

pydantic.error_wrappers.ValidationError:1个用于SimpleModel的验证错误
threeWordsId
必填字段(类型= 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)

1 个答案:

答案 0 :(得分:2)

在配置中使用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')