---
title: "安装 PostGIS"
version: 4.0
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/4.0/ref/contrib/gis/install/postgis/
canonical: https://djangodocs.dev/zh-hans/4.0/ref/contrib/gis/install/postgis/
---
# 安装 PostGIS

[GEOS](/zh-hans/4.0/ref/contrib/gis/install/geolibs/#geosbuild)、[PROJ](/zh-hans/4.0/ref/contrib/gis/install/geolibs/#proj4) 和 [GDAL](/zh-hans/4.0/ref/contrib/gis/install/geolibs/#gdalbuild) 应在构建 PostGIS 之前安装。你可能还需要额外的库，参见 [PostGIS 要求](https://postgis.net/) 。

当使用 GeoDjango 和 PostGIS 时，需要使用 [psycopg2](https://www.psycopg.org/) 模块作为数据库适配器。

On Debian/Ubuntu, you are advised to install the following packages:
`postgresql-x.x`, `postgresql-x.x-postgis`, `postgresql-server-dev-x.x`,
and `python-psycopg2` (x.x matching the PostgreSQL version you want to
install). Alternately, you can [build from source](https://postgis.net/docs/postgis_installation.html#install_short_version). Consult the
platform-specific instructions if you are on [macOS](/zh-hans/4.0/ref/contrib/gis/install/#macos) or [Windows](/zh-hans/4.0/ref/contrib/gis/install/#windows).

## 安装后

### 创建一个空间数据库

PostGIS 2 包含了一个 PostgreSQL 的扩展，用来实现空间功能：

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

数据库用户必须是超级用户，才能运行 `CREATE EXTENSION postgis;`。该命令是在 [`migrate`](/zh-hans/4.0/ref/django-admin/#django-admin-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`](/zh-hans/4.0/ref/contrib/postgres/operations/#django.contrib.postgres.operations.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;
```
