0

I store Decimal numbers in JSONField with Django in order to have flexible amount of digits but then I'm unable to use them. This is how my model looks like.

from decimal import Decimal
# from django.core.serializers.json import DjangoJSONEncoder
import simplejson

class Order(models.Model):
    account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True)
    size = JSONField(null=True)

Following the recommendation from this answer https://stackoverflow.com/a/3148376/3423825 and store the value like this:

import simplejson as json
self.size = json.dumps(Decimal('1'), use_decimal=True)

Now when I try to convert it to decimal I get an error.

size = Decimal(self.size)

Object of type 'Decimal' is not JSON serializable

I must say I'm a bit lost because type(self.size) returns <class string> so I should be able to convert it to Decimal, or am'I missing something?

Thank you

Florent
  • 1,791
  • 22
  • 40
  • Why not use `DecimalField` instead? Your database will not be able to do any arithmetic operations on JSON fields, for one. – AKX Jul 22 '20 at 09:16
  • @AKX `DecimalField` is for a fixed-precision decimal number but my numbers have various precision of decimal number. – Florent Jul 22 '20 at 09:17
  • If you have an upper limit on the precision/number of digits you want to store, you can just set that for the field. – AKX Jul 22 '20 at 09:19
  • Yes but I need to store `Decimal('1')` as `1` and `Decimal('1.1')` as `1.1` in the same field. With `DecimalField` and `decimal_places=1`, `Decimal('1')` will be stored as `1.0` not `1` – Florent Jul 22 '20 at 09:22
  • If it's absolutely crucial to store e.g. `Decimal('42.000000')` verbatim, you might just want to subclass `CharField` or `TextField` to a `DecimalAsStringField`... – AKX Jul 22 '20 at 09:23

0 Answers0