GeoDjango 模型的最佳实践

Best practices for GeoDjango Models

我有一个经典的 GeoDjango 模型

from django.contrib.gis.db import models

class Location(models.Model):
  vessel    = models.ForeignKey(Vessel, on_delete=models.CASCADE)
  timestamp = models.DateTimeField(auto_now_add=True, blank=True)
  point     = models.PointField()

不过使用起来似乎很笨拙;

>>> foo = somevessel.location_set.create(point=Point(5, 23))
>>> foo.point.x
5.0

我仍然想将位置存储为一个点,但更愿意使用看起来更原生的代码与模型交互,例如

>>> foo = somevessel.location_set.create(latitude=5, longitude=12)
>>> foo.latitude
5.0

这是否违反最佳实践?在 Django 中有没有一种简单的方法可以实现这一点?

我认为像这样含蓄地形式化你的观点,即用纬度和经度 FloatFields, will not allow you to fully benefit from spatial lookup capabilities。如果不是 "bad practice",这很可能无法启动。

I still want to store the location as a point but would prefer to interact with the model with more native looking code,

为了以更原生的方式与模型交互,我会在我的模型中定义属性 class 实际上会 return 纬度 and/or 经度,做

from django.contrib.gis.db import models

class Location(models.Model):
  vessel    = models.ForeignKey(Vessel, on_delete=models.CASCADE)
  timestamp = models.DateTimeField(auto_now_add=True, blank=True)
  point     = models.PointField()

  @property
  def latitude(self):
      return self.point.x

  @property
  def longitude(self):
      return self.point.y

让你做

>>> foo = somevessel.location_set.create(point=Point(5, 23))
>>> foo.latitude
5.0