Skip to content

computed_field not present in model_json_schema #6564

@Galarzaa90

Description

@Galarzaa90

Initial Checks

  • I confirm that I'm using Pydantic V2 installed directly from the main branch, or equivalent

Description

When declaring a computed field (@computed_field), while the value is returned by model_dump_json, it is not present in the model_json_schema()

Every field that is part of the JSON response should be in the schema, as this could make validators that check for attributes not in the schema fail.

Example Code

import pydantic

class StudentGrades(pydantic.BaseModel):
    english: int
    history: int
    geography: int

    @computed_field()
    @property
    def grade(self) -> float:
        return (self.english + self.history + self.geography)/ 3

student = StudentGrades(english=80, geography=70, history=60)
print(student.model_dump_json())
# '{"english":80,"history":60,"geography":70,"grade":70.0}'
print(student.model_json_schema())
# {'properties': {'english': {'title': 'English', 'type': 'integer'}, 'history': {'title': 'History', 'type': 'integer'}, 'geography': {'title': 'Geography', 'type': 'integer'}}, 'required': ['english', 'history', 'geography'], 'title': 'StudentGrades', 'type': 'object'}

Python, Pydantic & OS Version

pydantic version: 2.0.2
        pydantic-core version: 2.1.2 release build profile
                 install path: /Users/allangalarza/PycharmProjects/detect-api/venv/lib/python3.9/site-packages/pydantic
               python version: 3.9.16 (main, Dec  7 2022, 10:06:04)  [Clang 14.0.0 (clang-1400.0.29.202)]
                     platform: macOS-13.4.1-arm64-arm-64bit
     optional deps. installed: ['typing-extensions']

Selected Assignee: @dmontagu

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2pendingIs unconfirmed

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions