What is the best django model field used to represent the amount in US dollars?

I need to save the amount of US dollars in US dollars in the Django model field. What is the best type of model field? I need the user to enter this value (with error checking, you only need the exact number to the cent), format it for output to users in different places and use it to calculate other numbers.

+78
django django-models
Jul 16 '09 at 18:23
source share
5 answers

The decimal field is the right choice for the currency value.

It will look something like this:

credit = models.DecimalField(max_digits=6, decimal_places=2) 
+127
Jul 16 '09 at 18:29
source share
โ€” -
 field = models.DecimalField(max_digits=8, decimal_places=2) 

Note that max_digits must be> = decimal_places. In this example, the value will have a value up to: 999,999.99

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

+33
Mar 29 '12 at 15:48
source share

Other answers are 100% correct, but not very practical, since you still have to manually control 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 }} 

Exit:

 $123.00 

It has a powerful backend via python-money and replaces standard decimal fields.

+27
May 27 '16 at a.m.
source share

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

  price = models.DecimalField(max_digits=8, decimal_places=2) @property def price_display(self): return "$%s" % self.price 
+6
Jul 29 '13 at 16:00
source share
 field = models.DecimalField(max_digits=8, decimal_places=2) 

Create a PostgreSQL field, for example:

  "field" numeric(8, 2) NOT NULL 

What is the best way to store PostGreSQL in US dollars.

If you need a double precision PostgreSQL field type, then you need to do the django model:

 field = models.FloatField() 
+1
Feb 18 '14 at 15:43
source share



All Articles