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

## 三元相似度

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

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

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

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

> **New in Django 4.0**

`trigram_word_similar` 查询允许你使用专用的 PostgreSQL 扩展来进行三元词相似性查询。它可以近似理解为测量参数和字段的任何子串之间共享的最大数量的三元组。三元组词查找被赋予一个表达式并返回具有大于当前相似度阈值的词相似度度量的结果。

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

`trigram_word_similar` 查询可用于 [`CharField`](/zh-hans/4.0/ref/models/fields/#django.db.models.CharField) 和 [`TextField`](/zh-hans/4.0/ref/models/fields/#django.db.models.TextField) ：

```
>>> Sentence.objects.filter(name__trigram_word_similar='Middlesborough')
['<Sentence: Gumby rides on the path of Middlesbrough>']
```

## `Unaccent`

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

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

`unaccent` 查找可以用在 [`CharField`](/zh-hans/4.0/ref/models/fields/#django.db.models.CharField) 和 [`TextField`](/zh-hans/4.0/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` 查找在大多数使用情况下应该可以正常进行。但是，使用该过滤器的查询一般会进行全表扫描，这对大表来说可能很慢。在这些情况下，使用专门的全文索引工具可能是合适的。
