【问题标题】:Django get coordinate values of PointFieldDjango获取PointField的坐标值
【发布时间】:2019-06-05 20:46:21
【问题描述】:

我想从以下queryset 中的点获取xy 坐标:

user = User.objects.values('id', 'email', 'username', 'point').first()

这些是我的models

from django.db.models import Model

from django.contrib.gis.db.models import PointField

class BasePointModel(Model):

    point = PointField(null=True, spatial_index=True, geography=True)

    class Meta:
        abstract = True

class User(AbstractUser, BasePointModel, HashableModel):  # type: ignore

    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = CharField(_("Name of User"), blank=True, max_length=255)
    is_online = BooleanField(_("Is online"), default=False)

我得到以下结果:

{'id': 85270,
 'email': 'username_0@email.com',
 'username': 'username_0',
 'point': <Point object at 0x7f8e061cc2b8>}

如何获得xy,使用values 进行查询集?

我想得到这样的东西:

{'id': 85270,
 'email': 'username_0@email.com',
 'username': 'username_0',
 'point__x': '-4.266398314110177',
 'point__y': '-39.39432682357033'}

我发出从数据库返回 50,000 行的请求,我注意到由于数据序列化,性能变得越来越差。我想通过返回values来最小化序列化。

但是PointField 总是返回一个object,而且我还没有找到以最佳方式对其进行序列化的方法。

【问题讨论】:

  • 显示User 的模型/字段和Point 的类。
  • @wim,我更新了我的问题。
  • 嘿@NarnikGamarnik 我正在通过我的答案,你觉得这里的任何答案有帮助吗?

标签: python django gis postgis geodjango


【解决方案1】:

您可以访问对象的__dict__ 方法,然后直接使用您的几何体:

user = User.objects.values('id', 'email', 'username', 'point').first()
user_dict = user.__dict__
user_dict.update({'point__x':user_dict['point'].x, {'point__y':user_dict['point'].y})

【讨论】:

    【解决方案2】:

    运气不好:/
    您将点设置为geography,因此您不能使用自定义GeoFunc 来在注释查询中应用PostGIS 的ST_XST_Y,因为它们仅适用于geometry 字段。

    为了在查询的values 结果中获取这些点的[lat, long] 值,我们可以使用点的GeoJSON 表示来注释查询并将它们作为值获取。为此,我们将使用AsGeoJSON 数据库函数:

    user = User.objects.annotate(
        point_as_json=AsGeoJSON('point')
    ).values('id', 'email', 'username', 'point_as_json').first()
    

    这将给我们以下结果:

    {
      'id': 85270,
      'email': 'username_0@email.com',
      'username': 'username_0',
      'point_as_json': {
        'type': 'Point',
        'coordinates': [-4.26639831, -39.39432682]
       }
    }
    

    作为旁注,您可以考虑增加 Django with django-rest-framework` 并在其基础上使用 django-rest-framework-gis,这在根据 GeoJSON 标准的序列化方面有一些非常方便的技巧。 em>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多