Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pydantic_mongo/abstract_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def to_document(model: T) -> dict:
:return: dict
"""
model_with_id = cast(ModelWithId, model)
data = model_with_id.model_dump()
data = model_with_id.model_dump(mode="json")
Copy link
Contributor

@KozyrevIvan KozyrevIvan Sep 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we should exclude computed_field here

This can be done for example like this:

computed_fields = set(model.model_computed_fields)
data = model_with_id.model_dump(
    mode="json", 
    exclude=computed_fields,
 )

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main issue I see is storing a Date object in mongo and also supporting a Enum. Converting it to JSON would convert the Date type into a "string" because JSON don't have Date times, its part of BSON.

data.pop("id")
if model_with_id.id:
data["_id"] = model_with_id.id
Expand Down
40 changes: 40 additions & 0 deletions test/test_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import mongomock
import pytest
from bson import ObjectId
from datetime import datetime, timezone
from enum import Enum
from pydantic import BaseModel, Field

from pydantic_mongo import AbstractRepository, PydanticObjectId
Expand Down Expand Up @@ -30,6 +32,22 @@ class Meta:
collection_name = "spams"


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


class Order(BaseModel):
id: Optional[PydanticObjectId] = None
created_at: datetime
state: Optional[State]


class OrderRepository(AbstractRepository[Order]):
class Meta:
collection_name = "orders"


@pytest.fixture
def database():
return mongomock.MongoClient().db
Expand Down Expand Up @@ -259,3 +277,25 @@ def test_paginate(self, database):

with pytest.raises(PaginationError):
spam_repository.paginate({}, limit=10, after="invalid string")

def test_store_enums(self, database):
order_repository = OrderRepository(database=database)
current_date = datetime.now(tz=timezone.utc)

order = Order(
state=State.Preparation,
created_at=current_date
)
order_repository.save(order)

mongo_document = database["orders"].find_one({
"_id": order.id,
})

assert mongo_document["state"] == "Preparation"
assert isinstance(mongo_document["created_at"], datetime)

find_result = order_repository.find_one_by_id(order.id)
assert find_result is not None
assert find_result.state == State.Preparation
assert find_result.created_at == current_date