Using custom trigram similarities with Django, Postgres and PgBouncer
I want to adjust pg_trgm.similarity_threshold
on some of my queries. But since I'm using PgBouncer (in transaction pooling mode) to mediate access to my Postgres database, I want to be sure that when I'm done, the session value is set back to the default.
Will this work?
from django.db import connection, transaction
from myapp.models import Something
def do_something(name):
full_query = """
select *
from myapp_something
where name %% %s
"""
with transaction.atomic():
with connection.cursor() as cursor:
cursor.execute("set local pg_trgm.similarity_threshold = 0.5")
return list(Something.objects.raw(full_query, name))
Asked another way...does the transaction block ensure that the cursor and the Something.objects.raw()
use the same connection?
Perhaps you can just wrap it all in a query with:
Something.objects.alias(
similarity = TrigramSimilarity('name', name)
).filter(similarity__gt=0.5).order_by('-similarity')
this also lets you use the Django ORM.