For a detailed exploration of Trigram Similarity, check out my previous blog.
Enhance Your Searches with PostgreSQL Trigram Similarity in Django.
Implementing trigram_similar lookups in Django ORM
First you need to enable pg_trgm extension in your PostgreSQL database to unlease the power of Trigram Similarity. To enable pg_trgm extension execute a following command in your terminal:
# Replace database_name with your actual database name
sudo -u postgres psql -d database_name -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"
Then add 'django.contrib.postgres' in settings.py file in django.
INSTALLED_APPS = [
...
'django.contrib.postgres',
]
A trigram_similar lookup is given an expression and returns results that have a similarity measurement greater than the current similarity threshold. The trigram_similar lookup can be used on CharField and TextField. Here’s how to use it:
# Creating Product Table for testing TrigramSimilarity
class Product(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
# Populating the Database with Sample Products
Product.objects.create(name='Espresso Machine')
Product.objects.create(name='Espresso Maker')
Product.objects.create(name='Expresso Machine')
Product.objects.create(name='Coffee Grinder')
Product.objects.create(name='Koffee Grinder')
Product.objects.create(name='Coffee Maker')
Product.objects.create(name='Cappuccino Maker')
Product.objects.create(name='Capuchino Maker')
Product.objects.create(name='French Press')
Product.objects.create(name='Frensh Press')
# Using trigram_similar lookup in Django ORM
Product.objects.filter(name__trigram_similar='Espresso')
# Result
[<Product: Espresso Machine>, <Product: Espresso Maker>, <Product: Expresso Machine>]
Top comments (0)