Decimal numbers in python/Django

14,457

Considering this model:

class Place(models.Model):
    name = models.TextField()
    description = models.TextField()
    longitude = models.DecimalField(max_digits=30, decimal_places=15)
    latitude = models.DecimalField(max_digits=30, decimal_places=15)

This should work (max number of allowed digits and decimal places used):

p = Place(
    name='Name',
    description='Description',
    latitude=0123456789012345.0123456789012345,
    longitude=0123456789012345.0123456789012345
)
p.save()

And this should fail (values over the top):

p = Place(
    name='Name',
    description='Description',
    latitude=01234567890123456.01234567890123456,
    longitude=01234567890123456.01234567890123456
)
p.save()

Make sure to have migrated/changed the database accordingly after changing your Django code.

Share:
14,457
Chris
Author by

Chris

Updated on June 24, 2022

Comments

  • Chris
    Chris almost 2 years

    I'm trying to do an insert in the database but it seems to be a problem with the Decimals.

    I have latitude and longitude, being an example like the following:

    latitude = models.DecimalField(max_digits=30, decimal_places=15)
    

    and then, when I try to do an insert I write:

    Place(name="center", description="study center", latitude=41.214555, longitude=2.121451)
    

    But I get that error: "quantize result has too many digits for current context"

    I should be able to have those numbers, right? I don't understand why I get that error. If someone can help me please I'd be really thankful.

  • Rohan
    Rohan almost 10 years
    What hints you that there is need for migration?
  • Artur Barseghyan
    Artur Barseghyan almost 10 years
    dev.mysql.com/doc/refman/5.1/en/… Taken MySQL as example, decimal column is added in the following way: CREATE TABLE my_table ( my_column DECIMAL(6, 4) UNSIGNED NOT NULL ); Django follows the specs, thus on the moment you make a column it takes the values of max_digits and decimal_places to create a proper column. If those values are changed, database should be changed accordingly.
  • Rohan
    Rohan almost 10 years
    Still not clear why you need migration, as OP does not mention he changed those values.
  • Artur Barseghyan
    Artur Barseghyan almost 10 years
    Assuming you initially had max_digits set to 6 and the decimal_places set to 4, your database would have the decimal column defined as DECIMAL(6,4). After changing your Django code to 15, 15 (for max_digits and decimal_places) in your database schema the column is still defined as to DECIMAL(6,4). And if data you try to insert into database doesn't meet those definitions, database "complains" to Django, thus you get an error. That's why you need to migrate in order to have the schema columns in sync with your Django code definitions.