Skip to content

Using different Enums (or Literal) on same data model, for different fields? #543

Answered by adhtruong
impaktor asked this question in Q&A
Discussion options

You must be logged in to vote

I think this is expected behaviour from polyfactory. For first idea, without type information on specific type so need to specify this explicitly.

For alternative, assuming pydantic 2 something like this might work. Note this is incomplete if you want to load data

from enum import Enum
from typing import TypeVar

from typing_extensions import Annotated

from pydantic import BaseModel, PlainSerializer

T = TypeVar("T", bound=Enum)
EnumSerialiser = Annotated[T, PlainSerializer(lambda x: {"@N": x.name, "@V": str(x.value)})]


class MyEnum(Enum):
    A = 1
    B = 2


class MyModel(BaseModel):
    field: EnumSerialiser[MyEnum]


print(MyModel(field=MyEnum.A).model_dump())

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@impaktor
Comment options

Answer selected by impaktor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants