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

Can't store datetime.timedelta #120

Open
nickleman opened this issue Mar 20, 2021 · 3 comments
Open

Can't store datetime.timedelta #120

nickleman opened this issue Mar 20, 2021 · 3 comments
Labels
bug Something isn't working

Comments

@nickleman
Copy link

The documentation does not state that datetime.timedelta is an excluded pydantic type, but when I try to save it to the MongoDB I get the following error:

bson.errors.InvalidDocument: cannot encode object: datetime.timedelta(seconds=21600), of type: <class 'datetime.timedelta'>

@nickleman
Copy link
Author

I had to make a custom validator that returns int to make this work. The ODMantic documentation refers to json encoders, but those don't seem to actually be used in the pipeline from a model to the MongoDB Engine. But the custom validator is. Now I just need to figure out if I can create a type based custom validator instead of a member based one without creating a custom type.

@nickleman
Copy link
Author

The custom validator isn't doing what I thought it was doing. It was replacing the timedelta with an integer in the model class, not just the database. Looking at the motor, I think I need to define a TypeEncoder for it, but I don't see how to add that in ODMantic.

@nickleman
Copy link
Author

Looks like I can do it with the following:

AsyncIOMotorClient(
    "mongodb://db_user:user_password@host:27017",
    type_registry=type_registry,
)

@art049 art049 added the bug Something isn't working label Sep 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants