BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
2.04k stars 215 forks source link

[BUG] Fields of type DecimalAnnotation are serialized to json as type number and deserialized as type float #735

Closed QSHolzner closed 1 year ago

QSHolzner commented 1 year ago

Describe the bug If the beanie DecimalAnnotation is used with a model class, then the Decimal values are written out as numbers and read in as floats when serializing to json. But if only Decimal is used, which is supported by Pydantic, then the value is written out in json as String and imported again as Decimal.

To Reproduce

Case 1 - DecimalAnnotation

from decimal import Decimal

from beanie import DecimalAnnotation
from pydantic import BaseModel

class MyModel(BaseModel):
    name: str
    value: DecimalAnnotation

def main() -> None:
    t1 = MyModel(name="t1", value=Decimal("1.4"))
    t_json = t1.model_dump_json(indent=2)
    print(t_json)
    t_imp_from_json = MyModel.model_validate_json(t_json, strict=True)
    print(t_imp_from_json.value, type(t_imp_from_json.value))

if __name__ == "__main__":
    main()

Console output:

{
  "name": "t1",
  "value": 1.4
}
1.4 <class 'float'>

Case 2 - Decimal

from decimal import Decimal

from pydantic import BaseModel

class MyModel(BaseModel):
    name: str
    value: Decimal

def main() -> None:
    t1 = MyModel(name="t1", value=Decimal("1.4"))
    t_json = t1.model_dump_json(indent=2)
    print(t_json)
    t_imp_from_json = MyModel.model_validate_json(t_json, strict=True)
    print(t_imp_from_json.value, type(t_imp_from_json.value))

if __name__ == "__main__":
    main()

Console output:

{
  "name": "t1",
  "value": "1.4"
}
1.4 <class 'decimal.Decimal'>

Expected behavior

The DecimalAnnotaton should behave like the Decimal type when serializing.

Additional context

In the DecimalCustomAnnotation class the float_schema is used. Is there a specific reason for this? If core_schema.decimal_schema() is used here then DecimalAnnotation behaves like the Decimal type when serializing / deserializing.


class DecimalCustomAnnotation:
    @classmethod
    def __get_pydantic_core_schema__(
        cls,
        _source_type: Any,
        _handler: Callable[[Any], core_schema.CoreSchema],  # type: ignore
    ) -> core_schema.CoreSchema:  # type: ignore
        def validate(value, _: FieldInfo) -> NativeDecimal:
            if isinstance(value, Decimal128):
                return value.to_decimal()
            if isinstance(value, str):
                return NativeDecimal(value)
            if isinstance(value, float):
                return NativeDecimal(str(value))
            return value

        python_schema: PlainValidatorFunctionSchema = core_schema.general_plain_validator_function(validate)  # type: ignore
        return core_schema.json_or_python_schema(
            json_schema=core_schema.decimal_schema(),
            python_schema=python_schema,
        )

    @classmethod
    def __get_pydantic_json_schema__(
        cls,
        _core_schema: core_schema.CoreSchema,  # type: ignore
        handler: GetJsonSchemaHandler,
    ) -> JsonSchemaValue:
        return handler(core_schema.decimal_schema())

DecimalAnnotation = Annotated[NativeDecimal, DecimalCustomAnnotation]
gsakkis commented 1 year ago

Does this work for pydantic v1?

QSHolzner commented 1 year ago

Does this work for pydantic v1?

This Type is only used for pydantic v2. For v1 the type DecimalAnnotation is an Alias of the Decimaltype

from beanie.odm.utils.pydantic import IS_PYDANTIC_V2

if IS_PYDANTIC_V2:
    from beanie.odm.custom_types.decimal import DecimalAnnotation
else:
    from decimal import Decimal as DecimalAnnotation