Skip to content
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

Storing enums #50

Open
aldoshkind opened this issue Dec 3, 2023 · 1 comment
Open

Storing enums #50

aldoshkind opened this issue Dec 3, 2023 · 1 comment

Comments

@aldoshkind
Copy link

Hi!
I faced problem with serializing enums: I get bson.errors.InvalidDocument: cannot encode object: <State.Preparation: 'Preparation'>, of type: <enum 'State'> when trying to store enum.

What is the correct solution?

Full example code:

from enum import Enum
from typing import Optional
from uuid import UUID, uuid4

from pydantic import BaseModel
from pydantic_mongo import AbstractRepository
from pymongo import MongoClient

client = MongoClient("localhost:27017", uuidRepresentation='standard')
database = client["pydantic_mongo_db"]
db = database["test_enum"]

class State(Enum):
    Preparation = 'Preparation'
    Processing = 'Processing'

class Info(BaseModel):
    id: UUID = uuid4()
    state: Optional[State] = State('Preparation')

class InfoRepository(AbstractRepository[ Info ]):
   class Meta:
      collection_name = 'info_repository'

repo = InfoRepository(db)

info = Info()

repo.save(info)
@Artucuno
Copy link
Contributor

Artucuno commented Dec 4, 2023

Hey there!

Here is the solution to your issue.

from enum import Enum
from typing import Optional

from pydantic import BaseModel
from pymongo import MongoClient

from pydantic_mongo import AbstractRepository, ObjectIdField

client = MongoClient("localhost:27017")
database = client["test_enum"]


class State(str, Enum):  # <---
    Preparation = 'Preparation'
    Processing = 'Processing'


class Info(BaseModel):
    id: ObjectIdField = None  # <---
    state: Optional[State] = State.Preparation


class InfoRepository(AbstractRepository[Info]):
    class Meta:
        collection_name = 'info_repository'


repo = InfoRepository(database=database)

info = Info()

repo.save(info)

res = [x for x in repo.find_by({})]
print(res)
for f in res:
    print(type(State(f.state)))

Artucuno added a commit to Artucuno/pydantic-mongo that referenced this issue Dec 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants