Reputation: 5198
So I'm just starting out with Django and using it to store forex prices which are represented as 1.21242
, 1.20641
, etc...
model.py
from django.db import models
# Create your models here.
class ForexPrice(models.Model):
openPrice = models.DecimalField(max_digits=6, decimal_places=6)
highPrice = models.DecimalField(max_digits=6, decimal_places=6)
lowPrice = models.DecimalField(max_digits=6, decimal_places=6)
closePrice = models.DecimalField(max_digits=6, decimal_places=6)
My Question Is:
How do the max_digits and decimal_places attributes work? I'm using 6 for both fields assuming max_digits=6
will allow values to be stored up to 6 digits ie: 123456.000000 while decimal_palces=6
will support values up to 000000.123456.
Is this assumption correct or am I missing something?
Getting the following error when I save the record to the DB:
A field with precision 6, scale 6 must round to an absolute value less than 1.
Upvotes: 10
Views: 21603
Reputation: 850
Here is a simple analysis
For the below expression in your model:
number = models.DecimalField(max_digits=6, decimal_places=2)
Here is the test & result
=> 9999.99 (correct)
=> 99999.99 (error: Ensure that there are no more than 6 digits in total)
=> 9999.999 (error: Ensure that there are no more than 6 digits in total)
=> 999.999 (error: Ensure that there are no more than 2 decimal places)
=> 99999.9 (error: Ensure that there are no more than 4 digits before the decimal point)
So, the above example shows that if we use max_digits=6
, you can enter total 6 digits as a field value.
As we have used decimal_places=2
, we have to think that we can store two decimal places as values, and the rest 6-2 = 4
will be the number of digits before the point.
In the case of:
number = models.DecimalField(max_digits=5, decimal_places=2)
We can store two decimal places as values, and the rest of 5-2 = 3
will be the number of digits before the point.
Upvotes: 1
Reputation: 1
"max_digits" represents the number of digits all of your numbers.
"decimal_places" represents the number of digits to the right of the comma.
For ex: to store numbers up to 999.99 with a resolution of 2 decimal places, you’d use:
models.DecimalField(..., max_digits=5, decimal_places=2)
Upvotes: 0
Reputation: 637
max_digits
must be equal, or higher than decimal_places
.
If you were to have 123456.654321 you'd have to define max_digits=12
, decimal_places=6
.
max_digits
is INCLUDING decimal_places
.
Upvotes: 35