-
-
Notifications
You must be signed in to change notification settings - Fork 408
Open
Description
Describe the bug
Discriminator does not work for polymorphic types
To Reproduce
Example schema:
openapi: 3.1.0
info:
title: Test
description: "Test API"
version: 0.0.0
paths:
/pet:
get:
responses:
'200':
description: "Pet"
content:
application/json:
schema:
$ref: "#/components/schemas/PetContainer"
components:
schemas:
PetContainer:
type: object
required:
- pet
properties:
pet:
$ref: "#/components/schemas/Pet"
Pet:
type: object
required:
- petType
properties:
petType:
type: string
oneOf:
- $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
- $ref: "#/components/schemas/Lizard"
discriminator:
propertyName: petType
mapping:
cat: "#/components/schemas/Cat"
dog: "#/components/schemas/Dog"
lizard: "#/components/schemas/Lizard"
Cat:
type: object
# all other properties specific to a `Cat`
properties:
name:
type: string
Dog:
type: object
# all other properties specific to a `Dog`
properties:
bark:
type: string
Lizard:
type: object
# all other properties specific to a `Lizard`
properties:
lovesRocks:
type: boolean
Used commandline:
$ datamodel-codegen --input openapi.yaml --input-file-type openapi --output-model-type pydantic_v2.BaseModel --output schemas.py --snake-case-field --use-annotated --use-union-operator --target-python-version '3.11'
Expected behavior
from schemas import PetContainer, Cat
import json
json_data = """
{
"pet": {
"name": "Meow-Meow",
"petType": "cat"
}
}
"""
container = PetContainer.model_validate_json(json_data)
try:
cat_name = container.pet.name
except AttributeError:
cat_name = None
assert isinstance(container.pet, Cat)
assert cat_name == "Meow-Meow"
Version:
- OS: macOS
- Python version: 3.11
- datamodel-code-generator version: 35
Additional context
See https://github.com/zdenecek/openapi-discriminator-allof-demo
Metadata
Metadata
Assignees
Labels
No labels