odmantic icon indicating copy to clipboard operation
odmantic copied to clipboard

Can't store datetime.timedelta

Open nickleman opened this issue 4 years ago • 3 comments

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 avatar Mar 20 '21 01:03 nickleman

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 avatar Mar 21 '21 11:03 nickleman

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 avatar Apr 01 '21 22:04 nickleman

Looks like I can do it with the following:

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

nickleman avatar Apr 01 '21 23:04 nickleman