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

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

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

在 Debian/Ubuntu 上，建议安装以下软件包：`postgresql-x`、`postgresql-x-postgis-3`、`postgresql-server-dev-x` 和 `python3-psycopg3` （x 对应您想要安装的 PostgreSQL 版本）。或者，您可以使用 [从源代码构建](https://postgis.net/docs/postgis_installation.html#install_short_version) 的方法。如果您使用的是 [macOS](/zh-hans/6.0/ref/contrib/gis/install/#macos) 或 [Windows](/zh-hans/6.0/ref/contrib/gis/install/#windows)，请参考平台特定的说明。

## 安装后

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

PostGIS 包含一个用于启用空间功能的 PostgreSQL 扩展：

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

数据库用户必须是超级用户，才能运行 `CREATE EXTENSION postgis;`。该命令是在 [`migrate`](/zh-hans/6.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 栅格功能，还应激活 `postgis_raster` 扩展。你可以使用 [`CreateExtension`](/zh-hans/6.0/ref/contrib/postgres/operations/#django.contrib.postgres.operations.CreateExtension) 迁移操作安装该扩展，或直接运行 `CREATE EXTENSION postgis_raster;`。

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

### 管理数据库

要管理数据库，您可以使用 pgAdmin III 程序 (开始 ‣ PostgreSQL X ‣ pgAdmin III) 或 SQL Shell (开始 ‣ PostgreSQL X ‣ SQL Shell)。例如，要在 SQL Shell 中以 `postgres` 用户的身份创建一个名为 `geodjango` 的空间数据库和用户，可以执行以下命令：

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