Skip to content

Commit

Permalink
Merge pull request #41 from scottwoodall/master
Browse files Browse the repository at this point in the history
Add Decimal support
  • Loading branch information
nemesifier committed May 13, 2014
2 parents 7b6e7ff + d536e16 commit 0df13b5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
7 changes: 5 additions & 2 deletions django_hstore/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
except ImportError:
import json

from decimal import Decimal

import django
from django.db import models, connection
from django.utils import six
Expand Down Expand Up @@ -79,15 +81,16 @@ def update(self, *args, **kwargs):

def ensure_acceptable_value(self, value):
"""
- ensure booleans, integers, floats, lists and dicts are converted to string
- ensure booleans, integers, floats, Decimals, lists and dicts are
converted to string
- convert True and False objects to "true" and "false" so they can be
decoded back with the json library if needed
- convert lists and dictionaries to json formatted strings
- leave alone all other objects because they might be representation of django models
"""
if isinstance(value, bool):
return force_text(value).lower()
elif isinstance(value, int) or isinstance(value, float):
elif isinstance(value, (int, float, Decimal)):
return force_text(value)
elif isinstance(value, list) or isinstance(value, dict):
return force_text(json.dumps(value))
Expand Down
13 changes: 13 additions & 0 deletions tests/django_hstore_tests/tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import pickle
from decimal import Decimal

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

def test_decimal(self):
databag = DataBag(name='decimal')
databag.data['dec'] = Decimal('1.01')
self.assertEqual(databag.data['dec'], force_text(Decimal('1.01')))

databag.save()
databag = DataBag.objects.get(name='decimal')
self.assertEqual(databag.data['dec'], force_text(Decimal('1.01')))

databag = DataBag(name='decimal', data={'dec': Decimal('1.01')})
self.assertEqual(databag.data['dec'], force_text(Decimal('1.01')))

def test_number(self):
databag = DataBag(name='number')
databag.data['num'] = 1
Expand Down

0 comments on commit 0df13b5

Please sign in to comment.