Skip to content

Generating Json Schema for nested models that have overlapping model names. #1912

@alexvoronov

Description

@alexvoronov

Bug

I'm trying to generate a schema that includes several models that have nested models. The inner-most models have identical name, Params, but since they are used only inside the class, there is no name clash. However, when adding outer models to the same schema, both inner-most Params models end up in the same ref location: {'$ref': '#/definitions/Params'}, which I believe causes the error I see: KeyError: <class '__main__.A.Params'>.

I believe some fully-qualified path in '$ref' would resolve this, something like:

{'$ref': '#/definitions/A/Params'}
{'$ref': '#/definitions/B/Params'}

As a workaround, I wonder if there a way I can adjust prefix of each model independently? Or is there a way to put schema of nested classes "in-place", without creating a "$ref"?

Here is a complete minimal example:

from pydantic import BaseModel, schema


class A(BaseModel):
    class Params(BaseModel):
        a: int

    params: Params  # A.Params

class B(BaseModel):
    class Params(BaseModel):
        b: int

    params: Params  # B.Params


schema.schema([A])  # Works fine.
schema.schema([B])  # Works fine.
try:
    schema.schema([A, B])  # Two schemas together - does not work.
except KeyError as e:
    print(f"{e.__class__.__name__}: {str(e)}")
    """
    KeyError: <class '__main__.A.Params'>
    """

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.6.1
            pydantic compiled: True
               python version: 3.7.8 | packaged by conda-forge | (default, Jul 31 2020, 02:25:08)  [GCC 7.5.0]
                     platform: Linux-3.10.0-957.27.2.el7.x86_64-x86_64-with-centos-7.6.1810-Core
     optional deps. installed: ['typing-extensions']

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions