Skip to content

Commit 0df13b5

Browse files
committed
Merge pull request #41 from scottwoodall/master
Add Decimal support
2 parents 7b6e7ff + d536e16 commit 0df13b5

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

django_hstore/fields.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
except ImportError:
66
import json
77

8+
from decimal import Decimal
9+
810
import django
911
from django.db import models, connection
1012
from django.utils import six
@@ -79,15 +81,16 @@ def update(self, *args, **kwargs):
7981

8082
def ensure_acceptable_value(self, value):
8183
"""
82-
- ensure booleans, integers, floats, lists and dicts are converted to string
84+
- ensure booleans, integers, floats, Decimals, lists and dicts are
85+
converted to string
8386
- convert True and False objects to "true" and "false" so they can be
8487
decoded back with the json library if needed
8588
- convert lists and dictionaries to json formatted strings
8689
- leave alone all other objects because they might be representation of django models
8790
"""
8891
if isinstance(value, bool):
8992
return force_text(value).lower()
90-
elif isinstance(value, int) or isinstance(value, float):
93+
elif isinstance(value, (int, float, Decimal)):
9194
return force_text(value)
9295
elif isinstance(value, list) or isinstance(value, dict):
9396
return force_text(json.dumps(value))

tests/django_hstore_tests/tests.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
import pickle
3+
from decimal import Decimal
34

45
from django.db import transaction
56
from django.db.models.aggregates import Count
@@ -42,6 +43,18 @@ def test_hstore_dict(self):
4243
self.assertEqual(alpha.data, {'v': '1', 'v2': '3'})
4344
self.assertEqual(beta.data, {'v': '2', 'v2': '4'})
4445

46+
def test_decimal(self):
47+
databag = DataBag(name='decimal')
48+
databag.data['dec'] = Decimal('1.01')
49+
self.assertEqual(databag.data['dec'], force_text(Decimal('1.01')))
50+
51+
databag.save()
52+
databag = DataBag.objects.get(name='decimal')
53+
self.assertEqual(databag.data['dec'], force_text(Decimal('1.01')))
54+
55+
databag = DataBag(name='decimal', data={'dec': Decimal('1.01')})
56+
self.assertEqual(databag.data['dec'], force_text(Decimal('1.01')))
57+
4558
def test_number(self):
4659
databag = DataBag(name='number')
4760
databag.data['num'] = 1

0 commit comments

Comments
 (0)