Repository: pydantic/pydantic

Issue:
KeyError when having same Inner Class name in different Outer Class
### Checks

* [x] I added a descriptive title to this issue
* [x] I have searched (google, github) for similar issues and couldn't find anything
* [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug

<!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) -->

# Bug

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
             pydantic version: 1.5.1
            pydantic compiled: True
                 install path: C:\Users\Dell\AppData\Local\Programs\Python\Python37\Lib\site-packages\pydantic
               python version: 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)]
                     platform: Windows-10-10.0.18362-SP0
     optional deps. installed: ['typing-extensions']
```
---
First of all, pydantic is awesome and super useful! Kudos to all the contributors! However, an error occurred when I was accessing the `/openapi.json` endpoint when I was testing out my FastAPI server. 
The response models are located in the models.py file which looks like this.
```py
# models.py
from pydantic import BaseModel
from typing import List

class AModel(BaseModel):
    class _InnerClass(BaseModel):
        error_code: str = "012345"
        
    errors: List[_InnerClass] = _InnerClass()

class BModel(BaseModel):
    class _InnerClass(BaseModel):
        error_code: str = "123456"
        
    errors: List[_InnerClass] = _InnerClass()
```
The FastAPI server file looks like this.
```py
# main.pyimport models
from fastapi import FastAPI

app = FastAPI()

@app.get("/A", response_model=models.AModel)
async def ARoute():
    return models.AModel()


@app.get("/B", response_model=models.BModel)
async def BRoute():
    return models.BModel()
```
When I run the command `uvicorn main:app` and accessed the route `/openapi.json` the following traceback is returned:
```shell
Traceback (most recent call last):
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 384, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\applications.py", line 190, in __call__
    await super().__call__(scope, receive, send)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
    raise exc from None
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\exceptions.py", line 82, in __call__
    raise exc from None
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\starlette\routing.py", line 41, in app
    response = await func(request)
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\applications.py", line 143, in openapi
    return JSONResponse(self.openapi())
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\applications.py", line 128, in openapi
    servers=self.servers,
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\openapi\utils.py", line 350, in get_openapi
    flat_models=flat_models, model_name_map=model_name_map  # type: ignore
  File "c:\users\dell\appdata\local\programs\python\python37\lib\site-packages\fastapi\utils.py", line 26, in get_model_definitions
    model, model_name_map=model_name_map, ref_prefix=REF_PREFIX  # type: ignore
  File "pydantic\schema.py", line 455, in pydantic.schema.model_process_schema
  File "pydantic\schema.py", line 491, in pydantic.schema.model_type_schema
  File "pydantic\schema.py", line 185, in pydantic.schema.field_schema
  File "pydantic\schema.py", line 372, in pydantic.schema.field_type_schema
  File "pydantic\schema.py", line 614, in pydantic.schema.field_singleton_schema
  File "pydantic\schema.py", line 539, in pydantic.schema.field_singleton_sub_fields_schema
  File "pydantic\schema.py", line 412, in pydantic.schema.field_type_schema
  File "pydantic\schema.py", line 665, in pydantic.schema.field_singleton_schema
KeyError: <class 'models.AModel._InnerClass'>
```
I temporarily solved the issue by editing the `get_long_model_name` function in [file](https://github.com/samuelcolvin/pydantic/blob/master/pydantic/schema.py) of my local copy to use model.\_\_qualname\_\_ (only for python 3.3+) instead of model.\_\_name\_\_:
```py
...
def get_long_model_name(model: Type['BaseModel']) -> str:
    return f'{model.__module__}__{model.__qualname__}'.replace('.', '__')
...
```


Discussion:
Hi @ArcArcaman and thanks for reporting!
I feel like this issue has already been discussed and if I'm not mistaken [there is already a fix](https://github.com/samuelcolvin/pydantic/pull/2170) 😉 
Maybe you can have a look to check if it indeed solves your problem.
Happy holidays ❄️ 
Oh okay, thanks @PrettyWood! Yeah, it seems like it will solve my issue if the fix is merged. Sorry for the duplication, can't find it myself 😄 Happy holidays to you too ⛄ 

Resolving patch:
diff --git a/pydantic/schema.py b/pydantic/schema.py
--- a/pydantic/schema.py
+++ b/pydantic/schema.py
@@ -404,7 +404,7 @@ def get_flat_models_from_models(models: Sequence[Type['BaseModel']]) -> TypeMode
 
 
 def get_long_model_name(model: TypeModelOrEnum) -> str:
-    return f'{model.__module__}__{model.__name__}'.replace('.', '__')
+    return f'{model.__module__}__{model.__qualname__}'.replace('.', '__')
 
 
 def field_type_schema(


Test patch:
diff --git a/tests/test_schema.py b/tests/test_schema.py
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -2099,6 +2099,44 @@ class Model(BaseModel):
     }
 
 
+def test_multiple_models_with_same_name(create_module):
+    module = create_module(
+        # language=Python
+        """
+from pydantic import BaseModel
+
+
+class ModelOne(BaseModel):
+    class NestedModel(BaseModel):
+        a: float
+
+    nested: NestedModel
+
+
+class ModelTwo(BaseModel):
+    class NestedModel(BaseModel):
+        b: float
+
+    nested: NestedModel
+
+
+class NestedModel(BaseModel):
+    c: float
+        """
+    )
+
+    models = [module.ModelOne, module.ModelTwo, module.NestedModel]
+    model_names = set(schema(models)['definitions'].keys())
+    expected_model_names = {
+        'ModelOne',
+        'ModelTwo',
+        f'{module.__name__}__ModelOne__NestedModel',
+        f'{module.__name__}__ModelTwo__NestedModel',
+        f'{module.__name__}__NestedModel',
+    }
+    assert model_names == expected_model_names
+
+
 def test_multiple_enums_with_same_name(create_module):
     module_1 = create_module(
         # language=Python