---
title: "PostgreSQL 特有查找"
version: 3.2
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/3.2/ref/contrib/postgres/lookups/
canonical: https://djangodocs.dev/zh-hans/3.2/ref/contrib/postgres/lookups/
---
# PostgreSQL 特有查找

## 三元相似度

`trigram_similar` 允许你使用专用的 PostgreSQL 扩展来执行三元查找，测量共享的 trigram（三个连续字符）的数量。给定一个表达式进行三元查找，并返回相似度测量大于当前相似度阈值的结果。

要使用它，请在你的 [`INSTALLED_APPS`](/zh-hans/3.2/ref/settings/#std-setting-INSTALLED_APPS) 中添加 `'django.contrib.postgres'`，并激活 PostgreSQL 上的 [pg\_trgm 扩展](https://www.postgresql.org/docs/current/pgtrgm.html) 。你可以使用 [`TrigramExtension`](/zh-hans/3.2/ref/contrib/postgres/operations/#django.contrib.postgres.operations.TrigramExtension) 迁移操作来安装该扩展。

`trigram_similar` 查找可以用于 [`CharField`](/zh-hans/3.2/ref/models/fields/#django.db.models.CharField) 和 [`TextField`](/zh-hans/3.2/ref/models/fields/#django.db.models.TextField)：

```
>>> City.objects.filter(name__trigram_similar="Middlesborough")
['<City: Middlesbrough>']
```

## `Unaccent`

`unaccent` 查找允许你使用一个专门的 PostgreSQL 扩展来执行不区分重音的查找。

这个查询是用 [`Transform`](/zh-hans/3.2/ref/models/lookups/#django.db.models.Transform) 来实现的，所以它可以和其他查询函数连锁使用。要使用它，你需要在你的 [`INSTALLED_APPS`](/zh-hans/3.2/ref/settings/#std-setting-INSTALLED_APPS) 中添加 `'django.contrib.postgres'`，并激活 PostgreSQL 上的 [unaccent 扩展](https://www.postgresql.org/docs/current/unaccent.html) 。如果你想使用迁移来进行这个激活，可以使用 [`UnaccentExtension`](/zh-hans/3.2/ref/contrib/postgres/operations/#django.contrib.postgres.operations.UnaccentExtension) 迁移操作。

`unaccent` 查找可以用在 [`CharField`](/zh-hans/3.2/ref/models/fields/#django.db.models.CharField) 和 [`TextField`](/zh-hans/3.2/ref/models/fields/#django.db.models.TextField) 上：

```
>>> City.objects.filter(name__unaccent="México")
['<City: Mexico>']

>>> User.objects.filter(first_name__unaccent__startswith="Jerem")
['<User: Jeremy>', '<User: Jérémy>', '<User: Jérémie>', '<User: Jeremie>']
```

> **Warning**
>
> `unaccent` 查找在大多数使用情况下应该可以正常进行。但是，使用该过滤器的查询一般会进行全表扫描，这对大表来说可能很慢。在这些情况下，使用专门的全文索引工具可能是合适的。
