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

问题描述 投票:0回答:2

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

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

from_orm

如果别名存在,

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

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

pydantic.error_wrappers.ValidationError:SimpleModel 的 1 个验证错误
三字 ID
必填字段(类型=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)
orm sqlalchemy pydantic
2个回答
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')


0
投票

将 from_attributes=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:
        from_attributes=True
        orm_mode=True

simple_orm = SimpleOrm(three_words_id='abc')
simple_oops = SimpleModel.from_orm(simple_orm)
© www.soinside.com 2019 - 2024. All rights reserved.