安装 PostGIS

GEOSPROJGDAL 应在构建 PostGIS 之前安装。你可能还需要额外的库,参见 PostGIS 要求

The psycopg or psycopg2 module is required for use as the database adapter when using GeoDjango with PostGIS.

On Debian/Ubuntu, you are advised to install the following packages: postgresql-x, postgresql-x-postgis-3, postgresql-server-dev-x, and python3-psycopg3 (x matching the PostgreSQL version you want to install). Alternately, you can build from source. Consult the platform-specific instructions if you are on macOS or Windows.

Changed in Django 4.2:

Support for psycopg 3.1.8+ was added.

安装后

创建一个空间数据库

PostGIS 2 includes an extension for PostgreSQL that's used to enable spatial functionality:

$ createdb  <db name>
$ psql <db name>
> CREATE EXTENSION postgis;

数据库用户必须是超级用户,才能运行 CREATE EXTENSION postgis;。该命令是在 migrate 过程中运行的。另一种方法是在项目中使用迁移操作:

from django.contrib.postgres.operations import CreateExtension
from django.db import migrations


class Migration(migrations.Migration):
    operations = [CreateExtension("postgis"), ...]

如果打算在 PostGIS 3+ 上使用 PostGIS 栅格功能,还应该激活 postgis_raster 扩展。你可以使用 CreateExtension 迁移操作来安装扩展,或者直接运行 CREATE EXTENSION postgis_raster;

GeoDjango 目前没有利用任何 PostGIS 拓扑功能。如果你打算在某些时候使用这些功能,你也可以通过发出 CREATE EXTENSION postgis_topology; 来安装 postgis_topology 扩展。

管理数据库

To administer the database, you can either use the pgAdmin III program (Start ‣ PostgreSQL X ‣ pgAdmin III) or the SQL Shell (Start ‣ PostgreSQL X ‣ SQL Shell). For example, to create a geodjango spatial database and user, the following may be executed from the SQL Shell as the postgres user:

postgres# CREATE USER geodjango PASSWORD 'my_passwd';
postgres# CREATE DATABASE geodjango OWNER geodjango;