1

虽然这里记录了 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)
4

1 回答 1

6

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

于 2020-02-13T15:27:38.117 回答