After digging a bit deeper into the pydantic code I found a nice little way to prevent this. There is a method called field_title_should_be_set(...) in GenerateJsonSchema which can be subclassed and provided to model_json_schema(...).
I'm not sure if the way I've overwritten the method is sufficient for each edge case but at least for this little test class it works as intended.
from pydantic import BaseModel
from pydantic._internal._core_utils import is_core_schema, CoreSchemaOrField
from pydantic.json_schema import GenerateJsonSchema
class Test(BaseModel):
a: int
class GenerateJsonSchemaWithoutDefaultTitles(GenerateJsonSchema):
def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
return_value = super().field_title_should_be_set(schema)
if return_value and is_core_schema(schema):
return False
return return_value
json_schema = Test.model_json_schema(schema_generator=GenerateJsonSchemaWithoutDefaultTitles)
assert "title" not in json_schema["properties"]["a"]
Answer from lord_haffi on Stack OverflowAfter digging a bit deeper into the pydantic code I found a nice little way to prevent this. There is a method called field_title_should_be_set(...) in GenerateJsonSchema which can be subclassed and provided to model_json_schema(...).
I'm not sure if the way I've overwritten the method is sufficient for each edge case but at least for this little test class it works as intended.
from pydantic import BaseModel
from pydantic._internal._core_utils import is_core_schema, CoreSchemaOrField
from pydantic.json_schema import GenerateJsonSchema
class Test(BaseModel):
a: int
class GenerateJsonSchemaWithoutDefaultTitles(GenerateJsonSchema):
def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
return_value = super().field_title_should_be_set(schema)
if return_value and is_core_schema(schema):
return False
return return_value
json_schema = Test.model_json_schema(schema_generator=GenerateJsonSchemaWithoutDefaultTitles)
assert "title" not in json_schema["properties"]["a"]
You can do it in following way with Pydantic v2:
from pydantic import BaseModel, ConfigDict
def my_schema_extra(schema: dict[str, Any]) -> None:
for prop in schema.get('properties', {}).values():
prop.pop('title', None)
class Model(BaseModel):
a: int
model_config = ConfigDict(
json_schema_extra=my_schema_extra,
)
print(Model.schema_json())