some of the fields in a pydantic class are actually internal representation and not something I want to serialize or put in a schema. I am trying various methods to exclude them but nothing seems to work.
here's one approach where I use the exclue=True and exclude_schema=True of a Field
class MyItem(BaseModel):
name: str = Field(...)
data: str = Field(...)
class MyObject(BaseModel):
items_dict: dict[str, MyItem] = Field(..., exclude=True, exclude_schema=True)
@property
def items_list(self):
return list(self.items_dict.values())
@root_validator(pre=True)
@classmethod
def encode_decode_items(cls, values):
items = values.get('items_dict')
if isinstance(items, dict):
values['items_dict'] = list(items.values())
elif isinstance(items, list):
values['items_dict'] = validate_items(items)
return values
obj = MyObject(items_dict=[MyItem(name='item1', data='data1'), MyItem(name='item2', data='data2')])
print(json.dumps(obj.model_json_schema(), indent=2))
however in the schema the field is still there:
{
"$defs": {
"MyItem": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"data": {
"title": "Data",
"type": "string"
}
},
"required": [
"name",
"data"
],
"title": "MyItem",
"type": "object"
}
},
"properties": {
"items_dict": {
"additionalProperties": {
"$ref": "#/$defs/MyItem"
},
"exclude_schema": true,
"title": "Items Dict",
"type": "object"
}
},
"required": [
"items_dict"
],
"title": "MyObject",
"type": "object"
}