New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Discriminated union does not work with aliased literal field #3849
Comments
I think this is a duplicate of #3846. Apologies, I started writing this yesterday evening before the other issue was created. |
Spooky that we found a similar problem around the same time! 😅 If you'd like to confirm, you could try the tentative fix that I've proposed here to see if it fixes your issue too. If so then we could link both tickets to the same PR. |
I'll check this tomorrow at work, thanks! EDIT: Just tried it out and it doesn't seem to work for the example above 😞
|
Can confirm, just had this same issue today |
Hello, we are having the same issue.
|
Yes, it's fixed in pydantic-core and will be fixed in V2. |
It seems this is fixed in v2: from pydantic import BaseModel, Field
from typing import Union
from typing_extensions import Literal, Annotated
class Cat(BaseModel):
pet_type: Literal['cat'] = Field(alias='pet_type_alias')
name: str
class Dog(BaseModel):
pet_type: Literal['dog'] = Field(alias='pet_type_alias')
name: str
class Home(BaseModel):
pet: Annotated[Union[Dog, Cat], Field(discriminator='pet_type')]
cat = Cat(name="Mitzi", pet_type_alias='cat')
home = Home(pet=cat)
print(home)
#> pet=Cat(pet_type='cat', name='Mitzi') |
This should be fixed now in the just-released 1.10.8, which should be available through PyPI shortly. |
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.The text was updated successfully, but these errors were encountered: