0
votes

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?

2
instead of status_id: StatusId = StatusId.ACTIVE try status_id: StatusId = StatusId.ACTIVE.value - Abhishek

2 Answers

0
votes

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'}"
0
votes

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