[QUESTION] How to hide certain fields in Pydantic models? · Issue #1378 · tiangolo/fastapi
Fri Jul 08 2022 12:18:02 GMT+0000 (Coordinated Universal Time)
Saved by
@ade8850
from pydantic import BaseModel, Field
class CustomBaseModel(BaseModel):
def dict(self, **kwargs):
hidden_fields = set(
attribute_name
for attribute_name, model_field in self.__fields__.items()
if model_field.field_info.extra.get("hidden") is True
)
kwargs.setdefault("exclude", hidden_fields)
return super().dict(**kwargs)
class Book(CustomBaseModel):
author: str
title: str
genre: str = Field(..., hidden=True)
m = Book(
author="Antoine de Saint-Exupéry",
title="The Little Prince",
genre="Novella",
)
print(m.genre) # Novella
print(m.dict()) # {'author': 'Antoine de Saint-Exupéry', 'title': 'The Little Prince'}
content_copyCOPY
https://github.com/tiangolo/fastapi/issues/1378
Comments