[Answered ]-Django: how to load a fixture that contains Decimal

2👍

Argument localize is used for forms, not models.

class Job(models.Model):
    #...shortened
    joburl = models.URLField(max_length=250, blank=True, null=True)
    expirydate = models.DateField(auto_now=True, blank=True, null=True)
    salarymax = models.DecimalField(max_digits=8, decimal_places=2)
    salarymin = models.CharField(max_length=40, blank=True, null=True)
    salarytype = models.CharField(max_length=20, blank=True, null=True) 
    name = models.CharField(max_length=40, blank=True, null=True) 
    ...

Proper format of decimal numbers in fixtures are:

float

{
    "fields": {
        ...#shortened
        "pub_date": "2015-12-23",
        "salarymax": 58689.54,
        "salarymin": "50,164.66",
        "salarytype": "annually"
    },
    "model": "emplois.job",
    "pk": 1
},

formatted string

{
    "fields": {
        ...#shortened
        "pub_date": "2015-12-23",
        "salarymax": '58689.54',
        "salarymin": "50,164.66",
        "salarytype": "annually"
    },
    "model": "emplois.job",
    "pk": 1
},

In this case string cannot be localized.

Try this:

>>> from decimal import Decimal
>>> Decimal(58100.23)
Decimal('58100.2300000000032014213502407073974609375')
>>> Decimal('58100.23')
Decimal('58100.23')
>>> Decimal('58,100.23')
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    Decimal('58,100.23')
  File "/usr/lib/python3.5/_pydecimal.py", line 597, in __new__
    "Invalid literal for Decimal: %r" % value)
  File "/usr/lib/python3.5/_pydecimal.py", line 4032, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: '58,100.23'

Leave a comment