如何通过 pydantic 模式重命名键以响应数据库 - FastAPI
How to rename keys in response from database by pydantic schema - FastAPI
我在 models.py 中有来自数据库的模型:
class Something(Base):
__tablename__ = "something"
DATE = Column(Date, primary_key=True, index=True )
a = Column(String, primary_key=True, index=True)
b = Column(Integer, primary_key=True, index=True)
c = Column(Float, index=True)
d = Column(Integer, index=True)
e = Column(Integer, index=True)
f = Column(Float, index=True)
g = Column(Float, index=True)
h = Column(Integer, index=True)
和 schema.py 中的狂妄模型:
class Something(BaseModel):
DATE: date
a: str
b: int
c: float = None
d: int = None
e: int = None
f: float = None
g: float = None
h: int = None
class Config:
orm_mode = True
我通过 ORM 从数据库中获取数据,在 app.get() 中我声明响应模型=List[schema.Something],但我想从数据库中更改愚蠢的名称 -> a, b、c、d -> 更漂亮的名字。
是否有一些解决方案,例如在 NestJS 中映射名称?
尝试使用别名,这是 allow_population_by_field_name
选项允许的,例如:
class Person(BaseModel):
first_name: str = Field(..., alias='first')
last_name: str = Field(..., alias='second')
class Config:
allow_population_by_field_name = True
p = Person(**{'first': 'John', 'second': 'White'})
print(p.__dict__)
# {'first_name': 'John', 'last_name': 'White'}
我在 models.py 中有来自数据库的模型:
class Something(Base):
__tablename__ = "something"
DATE = Column(Date, primary_key=True, index=True )
a = Column(String, primary_key=True, index=True)
b = Column(Integer, primary_key=True, index=True)
c = Column(Float, index=True)
d = Column(Integer, index=True)
e = Column(Integer, index=True)
f = Column(Float, index=True)
g = Column(Float, index=True)
h = Column(Integer, index=True)
和 schema.py 中的狂妄模型:
class Something(BaseModel):
DATE: date
a: str
b: int
c: float = None
d: int = None
e: int = None
f: float = None
g: float = None
h: int = None
class Config:
orm_mode = True
我通过 ORM 从数据库中获取数据,在 app.get() 中我声明响应模型=List[schema.Something],但我想从数据库中更改愚蠢的名称 -> a, b、c、d -> 更漂亮的名字。 是否有一些解决方案,例如在 NestJS 中映射名称?
尝试使用别名,这是 allow_population_by_field_name
选项允许的,例如:
class Person(BaseModel):
first_name: str = Field(..., alias='first')
last_name: str = Field(..., alias='second')
class Config:
allow_population_by_field_name = True
p = Person(**{'first': 'John', 'second': 'White'})
print(p.__dict__)
# {'first_name': 'John', 'last_name': 'White'}