django存取空间结构数据

数据库

这里使用postgresql数据库,django使用pgsql需要使用psycopg2-binary模块

PostGIS插件

PostGIS是对象关系型数据库PostgreSQL的一个插件,PostGIS提供如下空间信息服务功能:空间对象、空间索引、空间操作函数和空间操作符, 包括:点(POINT)、线(LINESTRING)、多边形(POLYGON)、多点 (MULTIPOINT)、多线(MULTILINESTRING)、多边形(MULTIPOLYGON)和集合对象集 (GEOMETRYCOLLECTION)等。同时,PostGIS遵循OpenGIS的规范。

  • 安装

    yum install postgis2_96   # 因为安装的PostgreSQL版本为9.6,所以是postgis2_96
  • 为名为gisdb的数据库安装插件

    gisdb=# CREATE EXTENSION postgis;
    gisdb=# CREATE EXTENSION postgis_topology;
  • 检查数据库安装的插件

    dx  # 查看是否安装成功插件

fields

django为postgres提供了特殊的model fields,下面只是部分例子

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

class Map(models.Model):
    point_gis = PointField()
    gis_data = PolygonField()

字段写入

from django.contrib.gis.geos import Point, Polygon
from .models import Map

point = Point(x, y)  # 点坐标
gis = Polygon(((x1, y1), (x2, y2), (x3, y3), (x1, y1)))  # 闭合的多边形区域
Map.objects.create(point_gis=point, gis_data=gis)  

取出字段

point = Map.objects.get(pk=1).point_gis  # Point对象
point = point.coords  # 对象内容,可以通过索引取出x,y
>>>(x, y)

gis = Map.objects.get(pk=1).gis_data  # Polygon对象
gis = gis_data.coords  # 对象内容,可以通过循环取索引方式取值
>>>(((x1, y1), (x2, y2), (x3, y3), (x1, y1)),)
原文地址:https://www.cnblogs.com/jiaqi-666/p/11399086.html