Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with DecimalField, max_digits of django models

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?

like image 882
Madhu Nettem Avatar asked Nov 03 '17 19:11

Madhu Nettem


People also ask

What is DecimalField in Django?

DecimalField is a field which stores a fixed-precision decimal number, represented in Python by a Decimal instance. It validates the input using DecimalValidator.

How do I add a price field in Django?

Now Django does not have a built-in Price Field; however, a field which simulates money in Django can be easily created using the DecimalField. Django's DecimalField requires 2 parameters, one is max_digits and the other is decimal_places. max_digits is the total number of digits that is in the number specified.


2 Answers

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.

like image 108
cezar Avatar answered Oct 13 '22 00:10

cezar


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.

like image 40
Thusitha Deepal Avatar answered Oct 12 '22 23:10

Thusitha Deepal