For my FastAPI app, I’m trying to get Pydantic to validate my model with nested models in my item_config_descriptor field, but it doesn’t work. I should say that item_config_descriptor is not actually stored in the DB, but it is needed in the request body. I have this code.
Code
import datetime
import uuid
import ormar
from pydantic import BaseModel
class Items(ormar.Model):
"""
Registry of all items.
"""
class Meta(BaseMeta):
tablename: str = "items"
item_id: uuid.UUID = ormar.UUID(
primary_key=True, as_uuid=True, default=uuid.uuid4, uuid_format="string"
)
item_name: str = ormar.String(max_length=255, nullable=False)
item_type: str = ormar.String(max_length=255, nullable=False)
item_model: str = ormar.String(max_length=255, nullable=False)
item_vendor: str = ormar.String(max_length=255, nullable=False)
item_version: str = ormar.String(max_length=255, nullable=False)
item,_config_descriptor: ItemConfig = ormar.JSON(
nullable=True, pydantic_only=True
)
item_config_id: Optional[uuid.UUID] = ormar.UUID(
uuid_format="string", nullable=True
)
item_create_time: datetime.datetime = ormar.DateTime(
default=datetime.datetime.now
)
class ItemConfig(BaseModel):
"""
API schema for posting new Item Configurations.
"""
address: str
interfaces: dict[str, ItemConfigInterface]
class ItemConfigInterface(BaseModel):
"""
API schema for posting new Item Configuration Interfaces.
"""
name: str
mac_address: str
ip_address: str
POST that works as expected
If I send the following POST it works as expected.
{
"Item_name": "Test",
"Item_type": "DUR",
"Item_model": "Unknown",
"Item_vendor": "Unknown",
"Item_version": "Unknown",
"Item_config_descriptor": {
"address": "blah",
"interfaces": {
"i1": {
"name": "blah",
"mac_address": "blah",
"ip_address": "blah"
},
"i2": {
"name": "blah",
"mac_address": "blah",
"ip_address": "blah"
}
}
}
}
Item_config_descriptor is not being validated
If I make any change to my nested data, like change the key “interfaces” to “interfacesssss”, FastAPI still accepts my POST.
{
"Item_name": "Test",
"Item_type": "DUR",
"Item_model": "Unknown",
"Item_vendor": "Unknown",
"Item_version": "Unknown",
"Item_config_descriptor": {
"address": "blah",
"interfacessssss": {
"i1": {
"name": "blah",
"mac_address": "blah",
"ip_address": "blah"
},
"i2": {
"name": "blah",
"mac_address": "blah",
"ip_address": "blah"
}
}
}
}
How can I change it so that my nested model in item_config_descriptor is also validated?