In Django models, the FloatField
is a field type used to store floating-point numbers, which are numbers that can have a decimal point and can represent both whole and fractional parts. It is commonly used for fields where you need to store numeric data with decimal precision.
Let's say you add another field in the Demo model named field3.
class Demo(models.Model):
STATUS_CHOICES = (
(0, 'Inactive'),
(1, 'Active'),
(2, 'Pending'),
)
field1 = models.IntegerField()
field2 = models.BigIntegerField(null=True, blank=True)
field3 = models.FloatField()
default_value_field = models.SmallIntegerField(choices=STATUS_CHOICES, default=0)
even_number = models.IntegerField(validators=[validate_even_number])
You need to run python manage.py makemigrations
and python manage.py migrate
command to make the changes in the database.
python manage.py makemigrations
Here since, you are trying to add a non-nullable field inside the database, it needs to fill the existing rows with some value. In those cases django will show an error message like this, and will ask you to give a default value for only the existing instance or go back and give default values for that field itself. Here the value 0.0 is assigned for the existing rows in the database. For fields tgat allow null values, this does not need to be done.
python manage.py migrate
Lets retrieve the object and see it:
from datatypedemo.models import Demo
d=Demo.objects.get(id=1)
vars(d)
As you can see for field3, the value 0.0 is assigned automatically insted of None.
It also accepts the similar parameters such as blank
, null
, default
, validators
as the IntegerField.
The FloatField
is a versatile field in Django for storing numeric data with decimal precision. It allows you to represent a wide range of numeric values, making it suitable for various applications where accurate numerical data storage is required.