I'm working with Pydantic v2 and trying to include a computed field in both the schema generated by .model_json_schema() and the serialized output from .model_dump_json(). I've decorated the computed field with @property, but it seems that Pydantic's schema generation and serialization processes do not automatically include these properties.
Goal:
- Ensure the computed property is included in the JSON schema generated by
.model_json_schema(). - Ensure the computed property is included in the serialized JSON output from
.model_dump_json().
Current Approach:
Here's a simplified version of my model where I've defined a computed property full_name:
from pydantic import BaseModel, computed_field
class User(BaseModel):
first_name: str
last_name: str
@computed_field
@property
def full_name(self) -> str:
return f"{self.first_name} {self.last_name}"
Issues:
- When calling
User.model_json_schema(), thefull_namefield is not included in the schema.
To illustrate, here's how I'm attempting to generate the schema and serialize the model:
user_instance = User(first_name="John", last_name="Doe")
# Attempt to generate JSON schema
json_schema = User.model_json_schema()
print(json_schema) # 'full_name' is not included
# Attempt to serialize the model
serialized_output = user_instance.json()
print(serialized_output) # 'full_name' IS included
Question:
How can I modify my Pydantic model or process to ensure that the full_name computed property is included both in the schema and the serialized output? I am looking for a solution that works seamlessly with Pydantic v2's features and conventions.
The
modekeyword argument tomodel_json_schema()is'validation'by default and doesn't include computed fields,mode='serialization'does.Output:
Related GitHub issue: Including
computed_fieldin JSON schema?