From a4adf892dcb219aac811cd321dc40831a8fa243c Mon Sep 17 00:00:00 2001 From: Mostapha Sadeghipour Roudsari Date: Thu, 30 Apr 2020 13:56:11 -0400 Subject: [PATCH] Remove extra allOf keys in schema (#1438) resolves #1209 --- changes/1209-mostaphaRoudsari.md | 1 + pydantic/schema.py | 5 +++++ tests/test_schema.py | 16 ++++++++++++++++ 3 files changed, 22 insertions(+) create mode 100644 changes/1209-mostaphaRoudsari.md diff --git a/changes/1209-mostaphaRoudsari.md b/changes/1209-mostaphaRoudsari.md new file mode 100644 index 0000000..7d5293a --- /dev/null +++ b/changes/1209-mostaphaRoudsari.md @@ -0,0 +1 @@ +Remove extra `allOf` from schema for fields with `Union` and custom `Field`. diff --git a/pydantic/schema.py b/pydantic/schema.py index ec0a085..8157bac 100644 --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -559,6 +559,11 @@ def field_singleton_sub_fields_schema( known_models=known_models, ) definitions.update(sub_definitions) + if schema_overrides and 'allOf' in sub_schema: + # if the sub_field is a referenced schema we only need the referenced + # object. Otherwise we will end up with several allOf inside anyOf. + # See https://github.com/samuelcolvin/pydantic/issues/1209 + sub_schema = sub_schema['allOf'][0] sub_field_schemas.append(sub_schema) nested_models.update(sub_nested_models) return {'anyOf': sub_field_schemas}, definitions, nested_models diff --git a/tests/test_schema.py b/tests/test_schema.py index 3dd902a..5364405 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -960,6 +960,22 @@ def test_schema_overrides(): } +def test_schema_overrides_w_union(): + class Foo(BaseModel): + pass + + class Bar(BaseModel): + pass + + class Model_1(BaseModel): + a: Union[Foo, Bar] + + class Model_2(BaseModel): + a: Union[Foo, Bar] = Field(...) + + assert Model_1.schema()['properties'] == Model_2.schema()['properties'] + + def test_schema_from_models(): class Foo(BaseModel): a: str