What is the best django model field to use to represent a US dollar amount?

DjangoDjango Models

Django Problem Overview


I need to store a U.S. $ dollar amount in a field of a Django model. What is the best model field type to use? I need to be able to have the user enter this value (with error checking, only want a number accurate to cents), format it for output to users in different places, and use it to calculate other numbers.

Django Solutions


Solution 1 - Django

A https://docs.djangoproject.com/en/2.2/ref/models/fields/#decimalfield">decimal field is the right choice for the currency value.

It will look something like:

credit = models.DecimalField(max_digits=6, decimal_places=2)

Solution 2 - Django

The other answers are 100% right but aren't very practical as you'll still have to manually manage output, formatting etc.

I would suggest using django-money:

from djmoney.models.fields import MoneyField
from django.db import models


def SomeModel(models.Model):
    some_currency = MoneyField(
        decimal_places=2,
        default=0,
        default_currency='USD',
        max_digits=11,
    )

Works automatically from templates:

{{ somemodel.some_currency }}

Output:

$123.00

It has a powerful backend via python-money and it's essentially a drop-in replacement for standard decimal fields.

Solution 3 - Django

field = models.DecimalField(max_digits=8, decimal_places=2)

Note that max_digits should be >= decimal_places. This example setting would allow a value up to: 999,999.99

Docs: https://docs.djangoproject.com/en/1.10/ref/models/fields/#decimalfield

Solution 4 - Django

Define a decimal and return a $ sign in front of the value.

    price = models.DecimalField(max_digits=8, decimal_places=2)

    @property
    def price_display(self):
        return "$%s" % self.price
        

Solution 5 - Django

field = models.DecimalField(max_digits=8, decimal_places=2)

Should create a field for PostgreSQL like:

 "field" numeric(8, 2) NOT NULL

Which is the best way for PostGreSQL stored US dollar amount.

If you need a PostgreSQL field type "double precision", then you need do in django model:

field = models.FloatField()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeNView Question on Stackoverflow
Solution 1 - DjangosimplyharshView Answer on Stackoverflow
Solution 2 - DjangoMichael ThompsonView Answer on Stackoverflow
Solution 3 - DjangoLee HindeView Answer on Stackoverflow
Solution 4 - DjangocmelanView Answer on Stackoverflow
Solution 5 - DjangomanuelpgsView Answer on Stackoverflow