I am trying to update the descriptions of fields in my class such that the original field description is changed from what is defined in the Field function. The example code is below, unfortunately when I call model_json_schema it still prints out Meatball.
from pydantic import BaseModel, Field
class A(BaseModel):
@classmethod
def update_description(cls, field_name: str, new_description: str):
if field_name in cls.model_fields:
cls.model_fields[field_name].description = new_description
else:
raise ValueError(f"Field '{field_name}' does not exist in {cls.__name__}")
class B(A):
J: str = Field(description="MEATBALL")
B.update_description('J', 'Updated')
b_instance = B(J="A")
print(b_instance.model_json_schema())
Zachary Fontaine is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
When using pydantic
the Pydantic Field
function assigns the field descriptions at the time of class creation or class initialization like the __init__()
. It will show the model_json_schema()
as a default JSON object of some sort, which shows the initial description you mentioned this is because because the schema is cached.
Having said that I have modified your code to help you.
See docs on cls.model_rebuild()
rom pydantic import BaseModel, Field
class A(BaseModel):
@classmethod
def update_description(cls, field_name: str, new_description: str):
if field_name in cls.__fields__:
cls.__fields__[field_name].field_info.description = new_description
else:
raise ValueError(f"Field '{field_name}' does not exist in {cls.__name__}")
@classmethod
def model_json_schema(cls, *args, **kwargs):
cls.model_json_schema()
return super().model_json_schema(*args, **kwargs)
class B(A):
J: str = Field(description="MEATBALL")
# Update the field description
B.update_description("J", "Updated")
# Create an instance and print the JSON schema
b_instance = B(J="A")
print(b_instance.schema())
Result of Test:
{'title': 'B', 'type': 'object', 'properties': {'J': {'title': 'J', 'description': 'Updated', 'type': 'string'}}, 'required': ['J']}
4