Reputation: 1
I'm using Padantic v2, creating models, and then I provide the model_json_schema to other teams that need to make sure they provide all the required parameters.
Is there a way to get the validation_alias in the model_json_schema instead of the field name?
For example, this is my model:
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field, AliasPath
class Config(BaseSettings):
model_config = SettingsConfigDict(validation_alias=lambda field_name: field_name.lower())
a: int = Field(..., validation_alias=AliasPath("b", "c"))
schema = Config.model_json_schema()
Current schema:
{
"additionalProperties": false,
"properties": {
"a": {
"title": "A",
"type": "integer"
}
},
"required": [
"a"
],
"title": "Config",
"type": "object"
}
"a" does not exist in the source that I initialize the model with,
For example, this is the source: {"b": {"c": 3}}
On the other hand, I want to access "a" like this:
model.a
and not model.b.c
This is the desired schema:
{
"$defs": {
"ConfigB": {
"additionalProperties": false,
"properties": {
"c": {
"title": "C",
"type": "integer"
}
},
"required": [
"c"
],
"title": "ConfigB",
"type": "object"
}
},
"additionalProperties": false,
"properties": {
"b": {
"$ref": "#/$defs/ConfigB"
}
},
"required": [
"b"
],
"title": "Config",
"type": "object"
}
Thanks in advance
Upvotes: 0
Views: 48
Reputation: 1
I used @computed_field instead of using validation_alias=AliasPath(...), like this:
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field, AliasPath
class BModel(BaseSettings):
c: int
class Config(BaseSettings):
model_config = SettingsConfigDict(validation_alias=lambda field_name: field_name.lower())
b: BModel
@computed_field
@property
def a(self) -> int:
return self.b.c
schema = Config.model_json_schema()
schema
{
"$defs": {
"BModel": {
"additionalProperties": false,
"properties": {
"c": {
"title": "C",
"type": "integer"
}
},
"required": [
"c"
],
"title": "BModel",
"type": "object"
}
},
"additionalProperties": false,
"properties": {
"b": {
"$ref": "#/$defs/BModel"
}
},
"required": [
"b"
],
"title": "Config",
"type": "object"
}
Upvotes: 0