Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal numbers in python/Django

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.

like image 920
Chris Avatar asked Jul 02 '14 06:07

Chris


1 Answers

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.

like image 68
Artur Barseghyan Avatar answered Oct 10 '22 17:10

Artur Barseghyan