Django: How should I store a money value?

Question:

I’m running into a paradigm problem here. I don’t know whether I should store money as a Decimal(), or if I should store it as a string and convert it to a decimal myself. My reasoning is this:

PayPal requires 2 decimal places, so if I have a product that is 49 dollars even, PayPal wants to see 49.00 come across the wire. Django’s DecimalField() doesn’t set a decimal amount. It only stores a maximum decimal places amount. So, if you have 49 in there, and you have the field set to 2 decimal places, it’ll still store it as 49. I know that Django is basically type casting when it deserializes back from the database into a Decimal (since Databases don’t have decimal fields), so I’m not completely concerned with the speed issues as much as I am with the design issues of this problem. I want to do what’s best for extensibility.

Or, better yet, does anyone know how to configure a django DecimalField() to always format with the TWO_PLACES formatting style.

Asked By: orokusaki

||

Answers:

I think you should store it in a decimal format and format it to 00.00 format only then sending it to PayPal, like this:

pricestr = "%01.2f" % price

If you want, you can add a method to your model:

def formattedprice(self):
    return "%01.2f" % self.price
Answered By: Valentin Golev

I suggest to avoid mixing representation with storage. Store the data as a decimal value with 2 places.

In the UI layer, display it in a form which is suitable for the user (so maybe omit the “.00”).

When you send the data to PayPal, format it as the interface requires.

Answered By: Aaron Digulla

You store it as a DecimalField and manually add the decimals if you need to, as Valya said, using basic formatting techniques.

You can even add a Model Method to you product or transaction model that will spit out the DecimalField as an appropriately formatted string.

Answered By: M. Ryan

You might want to use the .quantize() method. This will round a decimal value to a certain number of places, the argument you provide specifies the number of places:

>>> from decimal import Decimal
>>> Decimal("12.234").quantize(Decimal("0.00"))
Decimal("12.23")

It can also take an argument to specify what rounding approach you want (different accounting systems might want different rounding). More info in the Python docs.

Below is a custom field that automatically produces the correct value. Note that this is only when it is retrieved from the database, and wont help you when you set it yourself (until you save it to the db and retrieve it again!).

from django.db import models
from decimal import Decimal
class CurrencyField(models.DecimalField):
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        try:
           return super(CurrencyField, self).to_python(value).quantize(Decimal("0.01"))
        except AttributeError:
           return None

[edit]

added __metaclass__, see Django: Why does this custom model field not behave as expected?

Answered By: Will Hardy

Money should be stored in money field, which sadly does not exist. Since money is two dimensional value (amount, currency).

There is python-money lib, that has many forks, yet I haven’t found working one.


Recommendations:

python-money probably the best fork https://bitbucket.org/acoobe/python-money

django-money recommended by akumria: http://pypi.python.org/pypi/django-money/ (havent tried that one yet).

Answered By: aisbaa

In my experience and also from others, money is best stored as combination of currency and the amount in cents.

It’s very easy to handle and calculate with it.

Answered By: Andre Bossard

Building on @Will_Hardy’s answer, here it is so you don’t have to specify max_digits and decimal_places every time:

from django.db import models
from decimal import Decimal


class CurrencyField(models.DecimalField):
  __metaclass__ = models.SubfieldBase

  def __init__(self, verbose_name=None, name=None, **kwargs):
    super(CurrencyField, self). __init__(
        verbose_name=verbose_name, name=name, max_digits=10,
        decimal_places=2, **kwargs)

  def to_python(self, value):
    try:
      return super(CurrencyField, self).to_python(value).quantize(Decimal("0.01"))
    except AttributeError:
      return None
Answered By: Dave Aaron Smith

My late to the party version that adds South migrations.

from decimal import Decimal
from django.db import models

try:
    from south.modelsinspector import add_introspection_rules
except ImportError:
    SOUTH = False
else:
    SOUTH = True

class CurrencyField(models.DecimalField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, verbose_name=None, name=None, **kwargs):
        decimal_places = kwargs.pop('decimal_places', 2)
        max_digits = kwargs.pop('max_digits', 10)

        super(CurrencyField, self). __init__(
            verbose_name=verbose_name, name=name, max_digits=max_digits,
            decimal_places=decimal_places, **kwargs)

    def to_python(self, value):
        try:
            return super(CurrencyField, self).to_python(value).quantize(Decimal("0.01"))
        except AttributeError:
            return None

if SOUTH:
    add_introspection_rules([
        (
            [CurrencyField],
            [],
            {
                "decimal_places": ["decimal_places", { "default": "2" }],
                "max_digits": ["max_digits", { "default": "10" }],
            },
        ),
    ], ['^application.fields.CurrencyField'])
Answered By: so_

I’m first-hands-on on Django and storing money values, too.

There is another possibility to store money values: just convert a money value to its minor representation and store that integer value in the database. If the rounding of the db backend can be adjusted to monetary arithmetic needs, this should work.

When retrieving a value, just read it back and represent it as a string as needed, which usually involves placing a decimal separator at the right position after converting the integer to a string.

It looks that some middleware exactly expects such behaviour Convert decimal to integer without losing monetary value.

Answered By: tdk

A better idea is to store money in minor currency units (smallest units possible). For euros and dollars the minor currency units are cents. There’s a Python (and Django) package called valuta based on the concept.

Using currency classes directly

import valuta

valuta.EUR.convert_to_currency_units(1_000)  # 1_000 is the price in cents
# 10.0

Working with string representations of the (ISO-4217) currency codes

from valuta.shortcuts import convert_to_currency_units

convert_to_currency_units("EUR", 1_000)  # 1_000 is the price in cents
# 10.0

Django integration

Model definition

from django.db import models
from valuta.contrib.django_integration.models import CurrencyField

class Product(models.Model):

    price = models.IntegerField()  # Amount in minor currency units
    price_with_tax = models.IntegerField()  # Amount in minor currency units
    currency = CurrencyField(amount_fields=["price", "price_with_tax"])

Sample data

import valuta
from product.models import Product
product = Product.objects.create(
    price=1_000,  # Price in cents
    price_with_tax=1_200,  # Price in cents
    currency=valuta.EUR.uid,
)

Use magic methods to convert from minor currency (cents) units to major currency units (euros)

product.price_in_currency_units()  # Price in euros
# 10.0
product.price_with_tax_in_currency_units()  # Price in euros
# 12.0

If you need to display it in templates:

product.price_display_in_currency_units()  # Price in euros
# '10.00'
product.price_with_tax_display_in_currency_units()  # Price in euros
# '12.00'

Now try another currency (JPY).

product_jpy = Product.objects.create(
    price=1_000,  # Price in cents
    price_with_tax=1_200,  # Price in cents
    currency=valuta.JPY.uid,
)

product.price_in_currency_units()  # Price in JPY
# 10.0
product.price_with_tax_in_currency_units()  # Price in JPY
# 12.0

product.price_display_in_currency_units()  # Price in JPY
# '10'
product.price_with_tax_display_in_currency_units()  # Price in JPY
# '12'
Answered By: Artur Barseghyan