在 Django 中使用哪个模型字段来存储经纬度值?

我想用经纬度来存储我的用户位置,目前这是来自谷歌地图,但我将使用 GeoDango 和一些点来计算点之间的距离。

然而,我首先感到困惑的是,我应该使用 Django 中的哪个字段来存储经纬度值?我得到的信息是相互矛盾的。

官方文档使用 FloatField Https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/#geographic-models

lon = models.FloatField()
lat = models.FloatField()

几乎所有关于堆栈溢出的答案都显示 DecimalField

long = models.DecimalField(max_digits=8, decimal_places=3)
lat = models.DecimalField(max_digits=8, decimal_places=3)

那我该用什么?

52608 次浏览

Float is generally an approximation, see here for some simple examples. You could get very nice results modifying your model to something like DecimalField(max_digits=9, decimal_places=6), since decimals are very important in coordinates but using more than 6 is basically meaningless.

The suggestion here to use DecimalField(max_digits=9, decimal_places=6) resulted in errors for me when trying to save locations from Google Maps.

If we assume that the most common use case is retrieving point locations from the Maps API, and a typical URL from Google Maps when right-clicking and selecting "What's Here?" yields something like:

https://www.google.com/maps/place/37°48'52.3"N+122°17'09.1"W/@37.814532,-122.2880467,17z

(random place)

So the longitude has 15 places before and after the decimal, which is why the accepted answer doesn't work. Since there's no reason to validate for "as short as possible" and db storage is cheap, I'm using:

    max_digits=22,
decimal_places=16)