Created
November 11, 2015 16:19
-
-
Save mjtamlyn/c6e20959eba8272c8587 to your computer and use it in GitHub Desktop.
Word matching Django func
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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