Issue with DecimalField, max_digits of django models
Solution 1
DecimalField
accepts arguments for max_digits
which is the total number of digits in a decimal number and for decimal_places
which is the number of decimal places.
If you define max_digits
to be 3 and decimal_places
to be 2, the largest number you can save is 9.99. It has 3 digits and 2 decimal places. If max_digits
is for example 5, and decimal_places
is 2, the largest number you can save is 999.99.
In your case it doesn't make sense to have maximum 2 digits and to have 2 decimal places, because it can't store 3.00, which has 3 digits. Because 2 digits are already occupied by the decimal places there is no space for digits before the dot. The largest number you can therefore save is 0.99.
Solution 2
these are the definition for max_digits and decimal_places
max_digits
The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value.
decimal_places
The maximum number of decimal places permitted.
Related videos on Youtube
Madhu Nettem
Updated on June 04, 2022Comments
-
Madhu Nettem almost 2 years
I have declared below field in models.py.
marks = models.DecimalField(max_digits=2, decimal_places=2, default=3.0)
At backend table structure is :
| Field | Type | Null | Key | Default | Extra | | marks | float(3,1) | NO | | 1.0 | |
So here default value 3.0 will try to save as 3.00 (decimal places=2) at backend and there will be no space to store left side value 3 right?
For above case,when I give max_digits=3 or decimal_places=1 it is working.
Please help me, whatis exactly happening here from django to mysql db flow?
-
Mauricio Cortazar over 6 yearsdid you run makemigrations and then migrate?, check the migration file
-
Madhu Nettem over 6 yearsYes.I did migration too.
-