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

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

Closed
QSHolzner opened this issue Oct 9, 2023 · 2 comments · Fixed by #738

Comments

@QSHolzner
Copy link

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
Copy link
Contributor

gsakkis commented Oct 9, 2023

Does this work for pydantic v1?

@QSHolzner
Copy link
Author

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

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

Successfully merging a pull request may close this issue.

2 participants