Skip to content

Instantly share code, notes, and snippets.

@mjtamlyn
Created November 11, 2015 16:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mjtamlyn/c6e20959eba8272c8587 to your computer and use it in GitHub Desktop.
Word matching Django func
from django.db.models import Func
class WordMatch(Func):
"""Combination function which checks whether any non-empty words are in common.
Roughly equivalent to bool(set(a.split()) & set(b.split())), but with MOAR sql.
"""
sql_template = "array_length(array_remove(array(select unnest(string_to_array(%s, ' ')) intersect select unnest(string_to_array(%s, ' '))), ''), 1) >= 1"
output_field = models.BooleanField()
def as_sql(self, compiler, connection):
first, second = self.source_expressions
first_sql, first_params = compiler.compile(first)
second_sql, second_params = compiler.compile(second)
return self.sql_template % (first_sql, second_sql), first_params + second_params
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment