0

I have some object with Pydantic's class. I have to create dict from object.

from enum import Enum

from pydantic import BaseModel


class StatusId(Enum):
    ACTIVE: int = 1
    PASSIVE: int = 2


class Pamagite(BaseModel):
    status_id: StatusId = StatusId.ACTIVE
    another_field: str = "another_field"

If I try do like this:

pamagite = Pamagite().dict()

I will get

pamagite = {'status_id': <StatusId.ACTIVE: 1>, 'another_field': 'another_field'}

I expected that pamagite will be equally to

pamagite = {'status_id': 1, 'another_field': 'another_field'}

How I can do this?

  • instead of `status_id: StatusId = StatusId.ACTIVE` try `status_id: StatusId = StatusId.ACTIVE.value` – Abhishek Jul 27 '22 at 13:34
  • 1
    Does this answer your question? [Pydantic enum field does not get converted to string](https://stackoverflow.com/questions/65209934/pydantic-enum-field-does-not-get-converted-to-string) – Paweł Rubin Jul 27 '22 at 13:52

2 Answers2

0

here,

class Pamagite(BaseModel):
    status_id: StatusId = StatusId.ACTIVE.value
    another_field: str = "another_field"

Calling the dict over the class object will give you

{'status_id': 1, 'another_field': 'another_field'}

Calling StatusId.ACTIVE.value will give you 1 and calling StatusId.ACTIVE.name will give you ACTIVE in case if you want to use ACTIVE instead of 1

Abhishek
  • 423
  • 6
  • 12
0

Use use_enum_values = True option.

whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialise model.dict() later (default: False)

from enum import Enum

from pydantic import BaseModel


class StatusId(Enum):
    ACTIVE: int = 1
    PASSIVE: int = 2


class Pamagite(BaseModel):
    status_id: StatusId = StatusId.ACTIVE
    another_field: str = "another_field"

    class Config:
        use_enum_values = True


pamagite = Pamagite().dict()

print(pamagite)  # "{'status_id': 1, 'another_field': 'another_field'}"
Paweł Rubin
  • 2,030
  • 1
  • 14
  • 25