Django Trigram Similarity for list of strings in Postgres

341 Views Asked by At

I have a list of names ["May", "Brown", "Chaplin", etc...] containing about 200 names. For each name string I want return a corresponding object from the database using Django TrigramSimilarity.

Normally I would do something like this:

result = []
for surname in surnames:
    person = Person.objects.annotate(
        similarity=TrigramSimilarity("surname", surname)
    )
    .filter(similarity__gt=0.3)
    .order_by("-similarity").first()

    if person:
        result.append(person)

but executing 200 queries in a row doesn't seem very optimal. Is there a way to create a single query for this operation? Also what are the ways to optimize this task even more?

Here is my Django model:

class Person(models.Model):
    name = models.Charfield(max_length=100)
    surname = models.Charfield(max_length=100)
    age = models.IntegerField()

    etc...
0

There are 0 best solutions below