Checks
Bug
Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.9.0
pydantic compiled: True
install path: /home/ljnsn/.virtualenvs/py39/lib/python3.9/site-packages/
pydantic
python version: 3.9.7 (default, Sep 10 2021, 14:59:43) [GCC 11.2.0]
platform: Linux-5.15.23-76051523-generic-x86_64-with-glibc2.34
optional deps. installed: ['typing-extensions']
It seems like the discriminator field for a discriminated union is only recognized when it is passed by its alias, even when allow_population_by_field_name = True. I would expect to be able to pass the discriminator field by field name, just like any other field, when that config option is set.
from typing import Literal, Union
from pydantic import BaseModel, Field
class Base(BaseModel):
class Config:
allow_population_by_field_name = True
class Cat(Base):
pet_type: Literal["cat"] = Field(alias="petType")
meows: int
class Dog(Base):
pet_type: Literal["dog"] = Field(alias="petType")
barks: float
class Lizard(Base):
pet_type: Literal["reptile", "lizard"] = Field(alias="petType")
scales: bool
class Model(Base):
pet: Union[Cat, Dog, Lizard] = Field(..., discriminator="pet_type")
n: int
print(Dog(**{"pet_type": "dog", "barks": 3.14}))
print(Model(pet={"petType": "dog", "barks": 3.14}, n=1))
print(Model(pet={"pet_type": "dog", "barks": 3.14}, n=1))
# > pydantic.error_wrappers.ValidationError: 1 validation error for Model pet
# Discriminator 'pet_type' is missing in value (type=value_error.discriminated_union.miss
# ing_discriminator; discriminator_key=pet_type)
Checks
Bug
Output of
python -c "import pydantic.utils; print(pydantic.utils.version_info())":It seems like the discriminator field for a discriminated union is only recognized when it is passed by its alias, even when
allow_population_by_field_name = True. I would expect to be able to pass the discriminator field by field name, just like any other field, when that config option is set.