Skip to content

Commit 7e86760

Browse files
committed
Handle serializing decimal.
1 parent 02fde50 commit 7e86760

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

django_unicorn/serializer.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
from decimal import Decimal
23
from functools import lru_cache
34
from typing import Dict, List
45

@@ -80,7 +81,7 @@ def _json_serializer(obj):
8081
Handle the objects that the `orjson` deserializer can't handle automatically.
8182
8283
The types handled by `orjson` by default: dataclass, datetime, enum, float, int, numpy, str, uuid.
83-
The types handled in this class: Django Model, Django QuerySet, any object with `to_json` method.
84+
The types handled in this class: Django Model, Django QuerySet, Decimal, or any object with `to_json` method.
8485
8586
TODO: Investigate other ways to serialize objects automatically.
8687
e.g. Using DRF serializer: https://www.django-rest-framework.org/api-guide/serializers/#serializing-objects
@@ -106,6 +107,8 @@ def _json_serializer(obj):
106107
return queryset_json
107108
elif PydanticBaseModel and isinstance(obj, PydanticBaseModel):
108109
return obj.dict()
110+
elif isinstance(obj, Decimal):
111+
return str(obj)
109112
elif hasattr(obj, "to_json"):
110113
return obj.to_json()
111114
except Exception as e:

tests/serializer/test_dumps.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
from decimal import Decimal
23

34
from django.db.models import (
45
SET_NULL,
@@ -42,6 +43,13 @@ def test_int():
4243
assert expected == actual
4344

4445

46+
def test_decimal():
47+
expected = '{"name":"123.1"}'
48+
actual = serializer.dumps({"name": Decimal("123.1")})
49+
50+
assert expected == actual
51+
52+
4553
def test_string():
4654
expected = '{"name":"abc"}'
4755
actual = serializer.dumps({"name": "abc"})

0 commit comments

Comments
 (0)