Support for dynamic fields equivalent to patternProperties in JSON Schema #3303
Replies: 3 comments 1 reply
-
did anything come of this, because this is so needed. Have a usecase right now, so really hoping someone took this seriously. |
Beta Was this translation helpful? Give feedback.
-
There's no built in support for pattern properties in v1 and it's too late to add it now. Happy to consider adding it it in v2, it would require a specific validator in rust. |
Beta Was this translation helpful? Give feedback.
-
I was able to do it directly in the model (pydantic v2). It follows The validator checks all fields for that annotation, then moves all matching properties from the root dict to that field. I've done it as a base class. The example class models class PropertyPattern:
def __init__(self, pattern: str) -> None:
self.pattern = pattern
class ModelWithPatternProperties(BaseModel):
@model_validator(mode='before')
@classmethod
def validate(cls, value: typing.Any, info: ValidationInfo):
for field_name, field_info in cls.model_fields.items():
pattern_anno = find_annotation_optional(field_info.metadata, PropertyPattern)
if not pattern_anno:
continue
pattern = re.compile(pattern_anno.pattern)
pattern_props = {}
for key, item in value.items():
if pattern.search(key):
pattern_props[key] = item
for key in pattern_props:
del value[key]
value[field_name] = pattern_props
return value
class Paths(ModelWithPatternProperties):
paths: Annotated[dict[str, PathItem], Field(default_factory=dict), PropertyPattern('^/')] |
Beta Was this translation helpful? Give feedback.
-
Our team uses Pydantic through FastAPI to check and process user JSON inputs.
In our data model, some keys are static but other are dynamic keys, that follows a pattern, provided by the user.
With JSON Schema validating such inputs can be done with patternProperties.
As far as I understand support for dynamic fields in Pydantic is very limited: #1809
It will be great to have a support of dynamically named fields in Pydantic.
I have a small working implementation LSerranoPEReN@abfc16c that can be converted to a PR if such feature is approved.
Here is an usage example which work our current implementation. It uses a new function named
PatternField
to declare such fields.Declaration
Schema generation
print(DistroFamily.schema_json(indent=4))
:Data processing
Beta Was this translation helpful? Give feedback.
All reactions