Django: How should I store a money value?
Asked Answered
G

10

65

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.

Groceryman answered 6/1, 2010 at 15:9 Comment(1)
re "since Databases don't have decimal fields"; Microsoft Sql Server has both "decimal" and "money" data types msdn.microsoft.com/en-us/library/aa258271%28v=sql.80%29.aspxSeaware
S
65

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?

Shaman answered 6/1, 2010 at 16:58 Comment(6)
Excellent. Thanks whrde. Is this all you have to do to have a fully functional custom model field? (ie, will this work exactly the same as DecimalField except for the formatting).Groceryman
Also, what is the convention for storing custom fields? I'm thinking I'll put it in the root project folder.Groceryman
Thanks, I just used this. I noticed I had to repeat the max_digits and decimal_places attributes every time I used CurrencyField, so I posted an answer that builds on yours to addresses this.Hayden
I wish you'd explain the rationale for quantize because neither your answer nor the python documentation makes that use clear to me.Kutenai
Ok, I've added a quick explanation for .quantize()Shaman
Updated in Django 1.8 - Now use from_db_value()Verwoerd
P
18

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
Patrolman answered 6/1, 2010 at 15:13 Comment(3)
Also: store the currency in the database as well as the amount. Money isn't just a number.Wingard
True that. Thanks Mr Shiny and NewGroceryman
Mr Shiny, you certainly don't need to store the currency in the database if you know that all the currencies are going to be the same. In fact, most applications don't deal with multiple currencies.Shaman
S
13

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'])
Scrubber answered 9/5, 2013 at 22:6 Comment(1)
Does the path in "['^application\.fields\.CurrencyField']" have to be changed according to my project? ThxHolub
S
12

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).

Sobriquet answered 23/7, 2012 at 11:43 Comment(1)
github.com/django-money/django-money is current, maintained and installs via pipPelayo
C
10

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.

Crystalcrystalline answered 6/1, 2010 at 15:14 Comment(0)
D
4

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.

Darindaring answered 1/11, 2012 at 11:22 Comment(5)
Be aware that it's not true for every currency that 1 minor (e.g. cent) equals 0.01 major (dollar).Fatherinlaw
I should not have used the term "cents", but more the smallest no further divisible unit of that currency.Darindaring
Still, this way your app won't support currencies with different ratio between major and minor at the same time.Fatherinlaw
@Fatherinlaw can you give an example of such a currency? Lets say one currency have 1000 minor for one major (1minor=0.001major), one could just store the currency precision as meta data.Proficient
@Proficient Japanese currency for example 1 rin = 0.001 yen. And you are right that currency precision should be stored as meta data exactly for this reasonFatherinlaw
H
4

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
Hayden answered 1/11, 2012 at 21:43 Comment(1)
I have a field similar to that, but I use the defaults = {... and defaults.update(**kwargs) pattern.Groceryman
B
1

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.

Bonbon answered 6/1, 2010 at 15:17 Comment(0)
L
0

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.

Larisalarissa answered 11/10, 2019 at 9:44 Comment(0)
D
0

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'
Dollar answered 15/6, 2021 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.